id
stringlengths
5
27
question
stringlengths
19
69.9k
title
stringlengths
1
150
tags
stringlengths
1
118
accepted_answer
stringlengths
4
29.9k
_cs.68300
I have the following question. Is the SAT solvers are deterministic?I mean, for example, about miniSAT and DPLL algorithm. Are they completely deterministic?If these algorithms will return unSAT it means that certainly the solution does not exist?
Deterministic SAT solver
algorithms;logic;satisfiability;sat solvers
null
_unix.204642
I can't boot my Windows XP OS on a dual boot with Windows XP and Ubuntu 14.04.2. I already tried the command update-grub without improving.I can see the menu entry in Grub but when I choose Windows XP to boot, the grub boot menu list pops out again without starting Windows. I can boot Ubuntu regularly.Here is the output from Boot info:Pastebin - Boot Info Script 0.61
Can't boot Windows XP from Grub2 in Ubuntu 14.04.2
ubuntu;windows;dual boot;grub
null
_webmaster.27036
we have an app running on heroku. the dns setup is like this:A record for domain.com -> heroku front end ip addressesCNAME for www.domain.com -> specific host name for our app provided by herokuwe also have an SSL cert for www.domain.com.the issue is that if someone goes to https://domain.com/secure_stuff, they will get heroku's SSL cert, instead of ours, causing lots of fear. We can do things on our end to make sure that all of our URLs point to https://www.domain.com, but it still won't solve this specific issue. is there a way to configure the DNS record to redirect all root domain traffic to the www subdomain?
DNS configuration to force root domain to www
dns;https;heroku
null
_unix.88109
I am happily using an old PC as a router. Two network cards, Debian wheezy, NAT, ... everything just fine. My home network uses static IPs, which I am also happy with.However, every box on my home network needs my provider's name servers in its own /etc/resolv.conf file for the internet to work. I thought this would be the way to go, but I notice that when using a notebook on a commercial router, the /etc/resolv.conf file gets overwritten once I dhclient to the router, and just the router's own IP address is listed, no external name servers.I figure that (1) the only way for this to work is that the router has some way of accepting the clients' name resolving requests and passes them on to the provider's name servers and (2) this is actually a quite handy solution because it would allow me to just put my router's IP into any client's /etc/resolv.conf and not worry about telling each client my provider's name servers.Are these assumptions (1, 2) correct?Is this a feature buried in DHCP requiring my router to be a DHCP server, or would it work with static IPs, too?What do I need to configure on my router in order to enable forwarding/handling my clients' name server requests?
What does my router need to act as a name server for my home network?
dns;router
null
_unix.103641
We have a small linux cluster (12 machines). Before we populate our database (then create a report from database contents) we would like to spell check a few files. The problem I have is some fields in the text file will contain lists of drugs and other medical terms and other acronyms that the spell checker will automatically think is a spelling error. Eg the lineDRUGS:=ASPIRIN;BISOPROLOL;RAMIPRIL;GTN;TAMSULOSIN;PIZOTIFEN;CO-CODAMOLWhen I issue the commandaspell --lang en_GB check filenameIt doesn't recognise most of these drugs?Is it possible to create a wordlist (i.e a text file containing a list of accepted drugs and acronyms) that aspell can use so that:(a) it ignores incorrectly spelled drugs(b) If a drug is mis-spelled it suggests the correctly spelled version
Linux adding wordlist for spell checking
aspell
Yes, you can add a personal wordlist with the --personal=FILE or -p parameter:aspell -p /path/to/my/wordlist check /path/to/the/file/to/checkYour personal wordlist should have one word per line.If you do not want to type the option each time, you can add it to your ~/.aspell.conf or /etc/aspell.conf.
_unix.6252
Debian's apt-get update fetches and updates the package index. Because I'm used to this way of doing things, I was surprised to find that yum update does all that and upgrades the system. This made me curious of how to update the package index without installing anything.
What is yum equivalent of 'apt-get update'?
package management;yum;apt
The check-update command will refresh the package index and check for available updates:yum check-update
_scicomp.4761
What is a good way to check if the any numerical error is occured in conjugate gradient algorithm. Additionally why is it not suggested to check error by checking A-orthogonality of search direction or checking orthogonality of residuals?Note: here by error I mean error from floating point unit of CPU because of incorrect computation (which can be due to corrupt data in cache etc.) not due to rounding error. In some cases the errors can be due incorrect computation of matrix vector product (in cases where matrix A is not explicitly available).
Checking for error in conjugate gradient algorithm
linear algebra;linear solver;iterative method;conjugate gradient
null
_codereview.165287
I was writing simple String class implementation (and it is quite ordinary), but I had found out that constructors, destructors and operator = are the most sensitive areas.So I wonder, if my implementation good in the sense of C++11/14 standard and are they efficient enough?String::String(){ m_characters = new char[0]; m_size = 0;}String::String( const int size ){ m_size = size; m_characters = new char[size];}String::String( const char* str ){ m_size = 0; int i = 0; while ( str[i] ) { m_size++; i++; } m_characters = new char[m_size]; for (int i = 0; i < m_size; i++) m_characters[i] = str[i];}String::String( const String& string ){ m_size = string.m_size; m_characters = new char[m_size]; for ( int i = 0; i < m_size; i++ ) m_characters[i] = string.m_characters[i];}String::~String(){ delete [] m_characters;} String& String::operator=( const String& string ){ if ( this != &string ) { m_size = string.m_size; m_characters = new char[m_size]; for (int i = 0; i < m_size; i++ ) m_characters[i] = string.m_characters[i]; } return *this;}I omit the header file because I think that class interface is quite clear. If required, I can attach it.UPD. SO does not allow me to put full code here, so I've put it on gist at github.
String class in C++
c++;strings;c++11;reinventing the wheel
null
_webapps.61060
The FAQ says:How many subgroups can I be a member of at one time? 50.How is it possible to get 51 groups?https://www.linkedin.com/anet?dispSortAnets=&trk=my_groups-h_gn-settings :
How is it possible to get 51 groups in LinkedIn?
linkedin;linkedin groups
It is actually possible to join up to 100 groups on LinkedIn, according to this post from someone who has joined 55 groups. She explains in a video in her post that you can join 50 parent groups and 50 subgroups. I checked a few of the groups in your screenshot, and I found that the Disruptive I.T. group is actually a subgroup of the Re-invent I.T. group. You are a member of both groups, and since Disruptive I.T. is a subgroup, that is how you are a member of more than 50 groups.
_codereview.117209
This function is meant to be used for reading files. It returns all bytes asked unless EOF is reached. It handles interrupts and returns -1 on errors.//safe function to read all bytes asked, only returns less bytes if EOFstatic ssize_t read_all(int fdes, void *buffer, size_t size){ ssize_t ret; ssize_t ret2; ret = read(fdes, buffer, size); if(ret == -1){ if(errno == EINTR) return read_all(fdes, buffer, size); return -1; } if(ret && ret != size){ ret2 = read_all(fdes, buffer + ret, size - ret); if(ret2 == -1) return -1; return ret + ret2; } return ret;}
Read function that properly handles interrupts
c
My main problem is the recursion. I don't think its major but I personally would use a loop. Given the current layout I can't quite convince myself that it works in all situations (especially since there are two alternative recursive calls).Declare variables close to the usage point (rather than everything at the top). ssize_t ret; ssize_t ret2;C has been updated so that you can declare variables at any point in a function. This helps in readability as you don't need to scroll far to find the variable declaration. Also if you declare in the most restrictive scope possible it helps to prevent data leaking (out of a scope).see: https://stackoverflow.com/a/8474123/14065Try this:static ssize_t read_all(int fdes, void* buffer, ssize_t size){ ssize_t totalRead = 0; while(totalRead != size) { ssize_t thisRead = read(fdes, buffer + totalRead, size - totalRead); if ((thisRead == -1) && (errno == EINTR)) { continue; } // Note: There are other errors that may not be erros. // EAGAIN or EWOULDBLOCK spring to mind but may need special handling // as immediately calling read may just cause a busy wait you may // want to suspend the thread by calling sleep.. if (thisRead == -1) { return -1; } if (thisRead == 0) { break; } totalRead += thisRead; } return totalRead;}
_softwareengineering.99774
I work as a rental agent / manager for a car rental company that is running on a rental system that was written in 1972. I decided that maybe it was time for an update. For a bit of background, here is a short example of the madness that we have to deal with from this program daily:A rental agent must remember that printing on one screen uses MXC in the ACT field (everything is based on short codes), which perplexingly stands for MaXimum display on a Contract, while on another it requires PR (for PRint) in the ACTION field, but several screens use a Y in the PT (for PrinT) field, yet another screen uses Y in the PRT (for PRinT) field, yet another screen requires the user to hit enter (but not the enter next to the letters, as that's a new line character, it must be the enter on the number pad) and then F8, a different but related screen requires simply F8, some screens have a field labeled PRT, which should be for PRinT, but the field actually does nothing and printing is done automatically after going through several prompts, and still more screens have a field labeled PRINT Y/N, which insanely defaults to Y for operations in which another location is already delivering paperwork, and to N for operations in which another dealer will need paperwork.I decided that I could do a better job than this, so I set out to contact the person in the company that would make the decision to update this. I eventually get through to the VP of IT, who is in charge of this program. I get a bit of information out of him, and learn that my car rental company has its rental program written in IBM mainframe assembler with a little bit of COBOL mixed in. He says that there are no positions open right now, but that I should e-mail him my resume anyway (in case something opens up).This leads me to my questions.The first is technical. With the idea of improving maintainability in the future, my thought is to re-write it in a higher-level language than assembly language. My area of experience is in C++, so that is the obvious choice for me. The company is in dire need of an easier way to update the program, as I recently read an article where the man I spoke with is quoted as saying the team worked hard, and they are proud to announce that the program now has support for 5-digit location codes (instead of 4) and 8 digit car numbers (instead of 7). My philosophy on updates, even in situations this dire, is in line with Joel's: http://www.joelonsoftware.com/articles/fog0000000069.html in short, re-writes should be incremental, rather than throwing out everything there was before and starting fresh.Is there an easy way to integrate IBM assembly with C++, and if so, how should I do it? I am vaguely aware of the asm keyword, but I don't know if it's best to use that or do something else. Is such a plan ill-advised? I do most of my work on Linux using g++ and GNU make, so answers specific to that are welcomed, but definitely not required (since I have no idea what sort of build system they have no, but I suspect almost none).The second question is more political. How should I go about persuading this company that they need to make the switch? The theoretical cost savings are huge (based on my estimates, the company is wasting an extra million or so dollars per year, just on increased training costs to learn how to interact with the program), but my proposed changes would probably put all of the current programmers out of work, should they be enacted, so there is great structural resistance to change.edit: I should explain why me modifying what the company already has seems like the best solution to me. I am still open to other suggestions, because this is a monster of a program, however. I've never had a programming job before, so please correct me on any incorrect analysis I might give.First off, there is the off-the-shelf solution.From my talks with a few mid-level managers about this sort of thing, one of the main concerns with switching to a new system is the large number of loyal employees who have been with the company for decades and are comfortable with the system by now. If I have the ability to modify what we have, I could maintain the current interface in a sort of 'compatibility mode'. Users already have to log in to use the current system, so I could add the ability to activate a setting when users log in for the 'first' time (after I make this change), where they are given the option to use either the 'classic' interface or the 'new' interface. There is no way I'll find an off-the-shelf solution that allows that, and I think that fears of senior employees getting confused by changing technology would be a major reason for upper management to say no.My company also owns the software we use; we do not license it. This means that the management I am currently talking to are the same people who could actually authorize me to make a change. With a third-party solution, I would have to get approval from my company in addition to securing whatever rights would be necessary from the company that developed the product we use, which adds an additional hurdle. This would also require convincing the company to give up on their product and take some other product, which seems like a greater hurdle than attempting to update what we have, but I could very well be wrong on this issue.Finally, looking into the future, I don't just want to improve the user interface and fix a few bugs. After I update those 'urgent' issues, I was hoping to update fundamental way the company runs as related to technology. After spending 1-2 years on these sorts of issues, my plan was to go back to management and propose more dramatic changes. There are many ways the company runs that could be fundamentally improved by technology that they simply are not using right now. For instance, each region pretty much operates the same way. The local major airport is the central hub to distribute cars. They are primarily sent on an as-needed basis. However, the airport is used as the home base for all operations. They'll send two people in one car to my location to pick up one car from us that we don't need, then return to the airport with the car they came in, plus what they are taking back (we are 32 miles from the airport). Then they will come to the location 5 miles away from us in two cars to drop one of them off, then return in their other car to the airport. They do this even if the car we sent back is the same kind of car they need near us. I've been with the company for about two years now, and I've only seem them deviate from this in the most extreme emergencies of car shortages (so about three times ever). I would replace the 4 people working in every region with an automated scheduling system that determines what cars go where and try and find the path that requires the least amount of time + miles + drivers to deliver all cars where they need to be, as an example of the higher level fixes I hope to some day add.However, before I would feel comfortable proposing all of this, I feel it would be helpful to get a toehold in the company and the code base by doing the smaller tasks, like updating the interface. Solutions like outsourcing or otherwise would remove this possibility.
Rewriting IBM assembler + COBOL in C++
c++;language agnostic;assembly;cobol
Confining myself to the technical front...I suggest you begin by determining the environment in which the application runs. Mainframe could mean a couple of different things, given the application's age it could be CICS or IMS. It's also possible the original authors wrote their own started task.Depending on where the application runs, it will likely make use of APIs for that environment, CICS now uses an interface markedly different from its early days, I cannot speak for IMS. If the application is its own started task, then it may very well have its own internal API - I spend some seven years supporting such a beast, written in the same era.Something else to consider, given the age of the application, is that the Assembler with which you wish to integrate C++ predates the existence of Language Environment (LE). As such, unless the Assembler has been updated to be LE-conforming, you will have some difficulty as C and C++ are LE-compliant and require their callers and callees to also conform.Another point for consideration, if this application is running on a moribund mainframe, you may be looking at trying to integrate with an application that runs on unsupported hardware and software. This would be not unlike trying to integrate with an application written in 1989 that runs on DOS 4.01 on its original hardware.
_unix.367774
I am really new to this whole shell programming, so I really don't understand much. I am supposed to write a shell script that will echo usernames of users whose primary group is equal to the group whose id is the argument of command line.
echo users with a specific gid
shell script;users;group
Since you're doing the lookup by GID, not by group name, and you're only interested in the primary GID for each user, this is trivially easy with Awk.The format of /etc/passwd is described in man 5 passwd. To quote the man page: There is one entry per line, and each line has the format: account:password:UID:GID:GECOS:directory:shellSo you want to print the first field for each line where the fourth field is what is passed in to your script. Where fields are delimited by colons.Personally I wouldn't bother with a script for this; I would use a shell function. See:In Bash, when to alias, when to script, and when to write a function?So all you need is:An understanding of the -F option for AwkA basic understanding of Awk's syntax, which is condition {action}An understanding of how to reference fields when using Awk, andIt will help if you have an understanding of how to pass shell variables to Awk; look into the -v option of Awk.Check the man page for Awk to get these points.I won't do your homework for youthe point is to learn to code, not learn to copy and paste. But if you get stuck on this please comment on this question. I can add a bit more detail if needed. (And in a week or so I can update to include a full solution.)Side note: in the real world, as you can see from the other answers, there is a lot more complexity associated with looking up users. Lots of different ways users can be stored, and accounting for those complexities can be...complex.But your question appears to be an assignment tailor-made to be easily accomplished with Awk, while also being a realistic application that would be useful in the real world.
_scicomp.26831
There is a paper called Density-equalizing map projections: Diffusion-based algorithm and applications by Michael T. Gastner and M. E. J. Newman, which explains their algorithm (which is based in diffusion equations) for generating value-by-area cartograms.While it explains the theoretical side of the mathematics involved with their algorithm, it doesn't explain how they actually implemented it. I tried to piece it together by looking at the source code from cart, but I don't have the programming knowledge (it's written in c, which I don't know) required to understand it.If anyone has at least a decent understanding of it and can explain the steps needed to create a cartogram using their algorithm, that would be greatly appreciated. Otherwise, if you have other helpful resources on the topic, those would be good too.
How is the Gastner-Newman equation implemented to create value-by-area cartograms?
linear algebra;fluid dynamics;nonlinear programming;diffusion;differential equations
null
_codereview.138111
I'm writing a todo app as a test. Having never done Ionic nor Angular apps before, I am not sure if I am following best practices here.What I have done is try to keep my controllers thin by placing all persistant logic in the model (service?). And instead of hard coding links in the view, I am calling a function in the controller.Are there any other things I should or shouldn't be doing?// controllersangular.module('starter.controllers', []).controller('TodosCtrl', function($scope, Todos, $state) { $scope.todos = Todos.all(); $scope.data = { showDelete: false }; $scope.add = function() { $state.go('tab.add'); }; $scope.remove = function(todo) { Todos.remove(todo); };}).controller('TodoDetailCtrl', function($scope, $stateParams, Todos, $state) { $scope.todo = Todos.get($stateParams.todoId); $scope.remove = function(todo) { Todos.remove(todo); $state.go('tab.todos'); };}).controller('TodoAddCtrl', function ($scope, $state, Todos) { $scope.content = {}; $scope.add = function() { var todo = $scope.content.name; if(todo) { $scope.content.name = ''; Todos.add({ id: Todos.all().length + 1, name: todo }); $state.go('tab.todos'); } };}).controller('AccountCtrl', function($scope) { // unused for now $scope.settings = { enableServer: true };})// servicesangular.module('starter.services', ['ngStorage']).factory ('StorageService', function ($localStorage) { $localStorage = $localStorage.$default({ todos: [] }); var _getAll = function () { return $localStorage.todos; }; var _add = function (todo) { $localStorage.todos.push(todo); } var _remove = function (todo) { $localStorage.todos.splice($localStorage.todos.indexOf(todo), 1); } return { getAll: _getAll, add: _add, remove: _remove };}).factory('Todos', function(StorageService) { // Might use a resource here that returns a JSON array var todos = StorageService.getAll(); return { all: function() { return todos; }, remove: function(todo) { StorageService.remove(todo); }, add: function(todo) { StorageService.add(todo); }, get: function(todoId) { for (var i = 0; i < todos.length; i++) { if (todos[i].id === parseInt(todoId)) { return todos[i]; } } return null; } };})
Simple Todo app
javascript;angular.js;to do list
For Angular Best Practices (or very good practice) take a look at John Papa's Style Guide:https://github.com/johnpapa/angular-styleguide/blob/master/a1/README.mdIt is well written, easy to understand, includes examples and really helps in development!Now to your code.FilesIn an actual application, you would put every single module, controller, service, and directive into a seperate file and name it accordingly.Basically, everytime you write angular.module, angular.controller, [...], it's a new file! This might seem ridiculously at first, but in a big project, it really helps to find stuff. A build chain, e.g. Gulp, will later put everything back together and even optimize it.Controller vs ServicesYou want the controller to have anything regarding the view. It includes callbacks (for ng-clicks e.g.) and maybe some logic that is very specific to the view. In the end, it is just a controller and just controlls what should happen and what the view should be able to use.Use a service/factory for all the real application logic. Everything that might be reusable gets a own service. Get data from the server? Service. Calculate something based on the user input? If it might be used somewhere else too, create a service! (GreatService.calculate(userInput)) This way you not only can use it again, but it also really helps you to test your logic in unit tests.In your specific Todo Example:I think you might have used too many controllers here. I dont's see your template, but this would be probably just fine with one controller and your service. Unless this has multiply states?Take a look at John Papa's style guide, it's worth !By the way, using $scope is not recommended. It does work, but is still a thing from the beginnings of Angular. Check this out: https://johnpapa.net/do-you-like-your-angular-controllers-with-or-without-sugar/
_codereview.110776
I'm writing a program to help with remembering complex bash commands. On invoking the program, it asks for a description of the desired operation, e.g., increase volume or find orphaned packages, and displays the commands matching the input ordered by closest match.Matching is determined by splitting the command text into a string vector, then the description, and combining these with a list of additional keywords to compare with the input via std::set_intersection. This is currently case sensitive, which I plan to change.This is my first C++ program so I've probably made plenty of mistakes. A couple things I'm still unclear on: when to pass arguments by reference, when to use const and static, and when to use pointers.#include <algorithm>#include <iostream>#include <map>#include <sstream>#include <string>#include <vector>struct Command { std::string text; std::string description; std::vector<std::string> addl_keywords;};struct FoundCommand { std::vector<std::string>::size_type keywords_found; Command command; FoundCommand(std::vector<std::string>::size_type keywords_found, Command command) : keywords_found {keywords_found}, command {command} {} bool operator < (FoundCommand other) { return keywords_found > other.keywords_found; } bool operator > (FoundCommand other) { return keywords_found < other.keywords_found; }};// TODO: make case insensitivestatic const Command commands[] { {amixer -Mq set Master 1%-, decrease volume, {lower}}, {amixer -Mq set Master 1%+, increase volume, {raise}}, {makepkg -sri, build and install a package using a PKGBUILD file, {pkgbuild}}, {makepkg -efi, rebuild and reinstall a package using a PKGBUILD file, {build, install, pkgbuild}}, {pacman -Qdt, list orphaned packages, {find, orphan}}, {pacman -Qe, list explicitly installed packages, {find, explicit}}, {pacman -Ql [package], list files owned by package, {find, own}}, {pacman -Qo [file], list packages that own file, {find, owned}}};std::vector<std::string> Split(const std::string& s, char delim = ' ') { std::stringstream ss {s}; std::string part; std::vector<std::string> parts; while (getline(ss, part, delim)) parts.push_back(part); return parts;}std::vector<std::string> Union(std::vector<std::string> v1, std::vector<std::string> v2) { std::vector<std::string> result; result.reserve(v1.size() + v2.size()); result.insert(result.end(), v1.begin(), v1.end()); result.insert(result.end(), v2.begin(), v2.end()); return result;}std::vector<std::string> Union(std::vector<std::string> v1, std::vector<std::string> v2, std::vector<std::string> v3) { return Union(Union(v1, v2), v3);}std::vector<std::string> Intersect(std::vector<std::string>& v1, std::vector<std::string>& v2) { std::sort(v1.begin(), v1.end()); std::sort(v2.begin(), v2.end()); std::vector<std::string> result; std::set_intersection(v1.begin(), v1.end(), v2.begin(), v2.end(), std::back_inserter(result)); return result;}std::vector<FoundCommand> FindCommands(std::vector<std::string>& input_keywords) { std::vector<FoundCommand> results; for (Command command : commands) { std::vector<std::string> cmd_keywords = Union(Split(command.text), Split(command.description), command.addl_keywords); std::vector<std::string> found_keywords = Intersect(input_keywords, cmd_keywords); if (!found_keywords.empty()) { results.emplace_back(found_keywords.size(), command); } } return results;}int main() { std::cout << Using keywords, describe what you would like to do: ; std::string input; getline(std::cin, input); std::vector<std::string> input_keywords = Split(input); std::vector<FoundCommand> results = FindCommands(input_keywords); std::sort(results.begin(), results.end()); for (FoundCommand result : results) std::cout << result.command.description << : << result.command.text << std::endl; return 0;}
Bash command helper in C++
c++;sorting;bash;search
null
_unix.371625
I understand that low-level NAND flash can effectively wear out and that an SD card controller (residing on the card itself) is responsible for managing the flash and exposing a comparatively simple interface to the host.Many have reported the case of a filesystem suddenly becoming read-only.How is a bad flash page detected at the SD card layer? How is this error passed to the filesystem? What is the mechanism by which the kernel detects this and makes the filesystem read-only?Is the error reported at the SD card layer specific? For example, ECC failed or the page could not be marked as bad? Or is it just: I can't read or write what was requested?We're having this issue with a root filesystem on an SD card. Sometimes the filesystem becomes read-only. Other times it doesn't but we observe corrupt files. Why weren't the corrupt files detected?
How does the kernel decide to make an SD card filesystem read-only?
filesystems;ext4;sd card;flash memory
null
_unix.70509
I am trying to write a script that will replace spaces with - and make all letters lower case for all files in the current directory. for x in 'ls' do if [ ! -f $x ]; then continue fi lc = `echo $x | tr '[A-Z]' '[a-z]'` if [ $lc != $x ]; then mv $x $lc fi donefind -name * * -type f | rename 's/ /-/g'I get the following output: call: rename from to files...However the names are not changing, example: 252680610243-Analyzed Sample2 2Jul12.txtI changed the permissions with chmod 706, would this be causing the issue? What am I missing here?Here is the output of bash -x lower.sh:+ for x in ''\''ls'\'''+ '[' '!' -f ls ']'+ continue+ find -name '* *' -type f+ rename 's/ /-/g'call: rename from to files...
Script to remove spaces and lowercase in file names
bash;find;text
null
_hardwarecs.2152
I have Asus RT-AC1200G+ router downstairs with my home media server connected with cable (Video streaming, NAS, VM streaming). On ground floor WiFi reception is very good (144MBit on 2,4 and over 350MBit on 5GHz).On second floor I have poor signal (unstable 60-80MBit on 2.4, very unstable 15MBit on 5GHz).What I want to have ground-floor quality signal on second floor. Router repositioning isn't an option - this is where internet cable is.Normally I would lay additional ethernet cable to upstairs and buy a good access point - but property owner strictly forbids doing it on my own and he demands ~250$ for it (+cable&AP price of course).House is pretty old, so PLC adaptor probably isn't a solution (however I haven't tested it yet).My question: is there a better solution than paying an owner to lay an ethernet cable for me and buy AP?
Gigabit WiFi on different floor
wifi;wireless
null
_codereview.70822
Of course the when this select is comes with less options it will be better to leave it like this, and when it comes more then this it better to make it via loop.The question is that if I should make it loop or leave it as it is ? which way is the best and why ?var htmlTemplate = <select class='action cycle' auto='1' value='24'> + <option value='6'>6 hours</option> + <option value='12'>12 hours</option> + <option value='24' selected=''>24 hours</option> + <option value='48'>48 hours</option> + <option value='72'>72 hours</option> + </select>;Also, in my current project I'm making 'Add' button which creates some html dom elements.My question is if I should leave the code inside string or create it via javascript (createElement) and again, I would like to know what is the best way and why :)var htmlTemplate = class='target-unit' identify='blahblah';htmlTemplate = <div + targetTemplate + > + <span class='target-place'> + targetPlace + </span> + <select class='action campaign'> + targetOptions + </select> + <label input-label='' class='target-limit'>5000</label> + <select class='action cycle' auto='1' value='24'> + <option value='6'>6 hours</option> + <option value='12'>12 hours</option> + <option value='24' selected=''>24 hours</option> + <option value='48'>48 hours</option> + <option value='72'>72 hours</option> + </select> + <button class='action small button-icon add flr no-title' identify='target-add'></button> + </div>;
Best practice of HTML DOM template in javascript
javascript;jquery;html
Personally I would create loops for this, it's very unreadable at the moment and you are repeating yourself a lot. Remember the DRY rule (don't repeat yourself). Also if you do it via loops it's easier to maintain and change in the future.
_unix.209990
I have a file in the following format:$ cat /tmp/raw2015-01 5000 10002015-02 6000 20002015-03 7000 3000Now, what I want is to get the combined value from columns 2 and 3 in each row so that results are as follows:2015-01 60002015-02 80002015-03 9000I tried this but it only shows last value in the file like 2015-03 value.
How can I combine values from two columns?
text processing
You can try using awk:awk '{ print $1, $2 + $3; }' /tmp/rawResult will be (I suppose value for 2015-03 should be 10000):2015-01 60002015-02 80002015-03 10000
_softwareengineering.342803
I could not find any official recommended indentation for the following idiom (straight from http://effbot.org/zone/python-with-statement.htm):with open(path) as f: data = f.read() do something with dataor:with open(path) as f: data = f.read()do something with dataIMHO, the first version is better at showing the scope, but the latter may prevent an excessive indentation. Is choosing one of those just a matter of taste? Or is there any authoritative source or established tradition to follow?As a side note, I cannot help but think that with is quite apart from the other block-constructing Python keywords. For instance, there is no question about choosing between:if condition: do something do something differentor:if condition: do somethingdo something differentSince they do... well, something different.
with open() as and indentation
python;coding style;indentation
I always use the second approach because it ensures that I don't hold the resource (file in your case) open longer than necessary.
_unix.129214
My eight month old Acer V3-571G is overheating: temperature fluctuates between 64 degC and 75 degC with only Firefox running and the exhausts are starting show some signs of melting. As soon as I launch Eclipse or Chrome, it reaches 80 degC. The main problem is that the high temperature threshold is set to 87 degC.I installed sensors and added acpi_osi=Linux to the boot line in Grub. However, sensors-detect only detects the coretemp-isa-0000 chip, and pwmconfig does not find any PWM capable sensor modules.Currently, I'm stuck with an overheating computer on which I cannot seem to control the fans.I know that the fans work because they turn much faster under Windows, making the computer cooler (and more noisy).I want to change the high temperature threshold from 87 degC to 65 or 70 degC.Here's the output of sensors (with only Firefox running on top of KDE4 on OpenSuse):# sensorscoretemp-isa-0000Adapter: ISA adapterPhysical id 0: +66.0C (high = +87.0C, crit = +105.0C)Core 0: +66.0C (high = +87.0C, crit = +105.0C)Core 1: +65.0C (high = +87.0C, crit = +105.0C)pkg-temp-0-virtual-0Adapter: Virtual devicetemp1: +66.0C nouveau-pci-0100Adapter: PCI adaptertemp1: +65.0C (high = +95.0C, hyst = +3.0C) (crit = +105.0C, hyst = +5.0C) (emerg = +135.0C, hyst = +5.0C)Creating /etc/sensors.d/foo with a temp entry seems to only change the reported temperature. I also tried setting the chip to an Intel PECI type (set temp1_type 6 (sensors -s is successful)) but that does not change the speed fans.I also tried editing /sys/class/hwmon/hwmon0/device/temp1_max but the file is read-only even for root.Any help or lead is appreciated! I prefer exhausting all possible resources before sending my computer back in because I need it for my day to day job, and I bought in another country than the one I'm currently in.
Lower temperature thresholds for sensors
opensuse;temperature;sensors;acer
null
_datascience.11002
If I understand correctly, the most_similar function computes the cosine similarity of the vector with all other vectors and finds the closest one. The vectors then viewed from a certain origin of (0,0,0,..0) for N dimensions (for N dimensional word vectors).Is there by any means that I could compute the angle of these vectors from the origin ?. If I compute the similarity between the vector and the origin vector and take the inverse cosine, will the resultant angle be the angle of the vector on origin space.If I get such an angle, on which plane does it lie as the vector is high dimensional.The reason is that, when we try to reduce it to 2 dimensions and plot them, only magnitude of the vector is considered right, so the direction information is missing. I would like to plot it in a polar plot to view both.Is there any such function in gensim?.
Compute angle of vector in word2vec models
dimensionality reduction;word embeddings;word2vec;gensim;cosine distance
null
_softwareengineering.235171
I've just begun reading The Art Of Unit Testing by Roy Osherove, and while I'm mostly finding the material very helpful, he makes a statement about not using messages in your Assert statements. Please never, ever, use this parameter. Just make sure your test name explains what's supposed to happen.My question is, in you experience do you find this advice to be good or bad? If you use assert messages in your unit tests, what information do you use it to capture beyond what a well named unit test could give you in the first place?
Assert Message in Unit Tests
unit testing;language agnostic;assertions
This sort of advice makes two key assumptions:You're going to be spending more time looking at some pass/fail summary of all your tests than the assert output.Your tests are only testing a single thing.Now #1 is pretty much guaranteed to be true. #2 is less often going to be true, even if it's good advice. The spirit of the advice is: you should be able to tell at a glance why your unit tests did not pass.The book's advice combines with these two assumptions to achieve the spirit of the advice. In my experience, this spirit is really what is key to follow. Once you have a good test name, and your test only tests one thing (even if you use multiple asserts to do it) - everything else is gravy.At that point, if you find it useful to use messages to differentiate asserts, go nuts. If you find it more useful to save time typing assert messages that nobody looks at, go nuts. The important thing is that you can tell at a glance what failed your tests.
_unix.344089
I enable the following line in the file /etc/apt/apt.conf.d/50unattended-upgrades according to the standard Debian wikio=Debian,n=jessie,l=Debian-Security;to get security updates automatically.Now I noticed that the line origin=Debian,codename=${distro_codename},label=Debian-Security;is enabled by default. What is this for? I'm worried because this comes right after the lines with stable code-name, which might get my Jessie to upgrade to Stretch in the background. So what does this line do?
Unattended upgrades config has a line enabled by default. What is it for?
debian;apt;unattended upgrades
That line enables unattended security updates for the currently installed release. As indicated in the comment at the start of the file,// Within lines unattended-upgrades allows 2 macros whose values are// derived from /etc/debian_version:// ${distro_id} Installed origin.// ${distro_codename} Installed codename (eg, jessie)So the line you added is redundant. The codename won't be interpreted as stable, so you won't upgrade to Stretch automatically.
_unix.104440
I have a command that I use from the CLI to properly color files, folders, executables, etc. The command that I'm executing looks like this:test -r ~/.dircolors && eval $(dircolors -b ~/.dircolors) || eval $(dircolors -b)I'd like to run this command from inside a script, but it does not work:#!/usr/bin/env bashtest -r ~/.dircolors && eval $(dircolors -b ~/.dircolors) || eval $(dircolors -b)How can I excute this command inside a script? I can't figure out why this command doesn't work from within a script?running /bin/bash -x myscript.sh produces the following output:$ /bin/bash -x myscript.sh+ test -r /home/turtle/.dircolors+ dircolors -b /home/turtle/.dircolorsLS_COLORS='no=00;38;5;244:rs=0:di=00;38;5;33:ln=01;38;5;37:mh=00:pi=48;5;230;38;5;136;01:so=48;5;230;38;5;136;01:do=48;5;230;38;5;136;01:bd=48;5;230;38;5;244;01:cd=48;5;230;38;5;244;01:or=48;5;235;38;5;160:su=48;5;160;38;5;230:sg=48;5;136;38;5;230:ca=30;41:tw=48;5;64;38;5;230:ow=48;5;235;38;5;33:st=48;5;33;38;5;230:ex=01;38;5;64:*.tar=00;38;5;61:*.tgz=01;38;5;61:*.arj=01;38;5;61:*.taz=01;38;5;61:*.lzh=01;38;5;61:*.lzma=01;38;5;61:*.tlz=01;38;5;61:*.txz=01;38;5;61:*.zip=01;38;5;61:*.z=01;38;5;61:*.Z=01;38;5;61:*.dz=01;38;5;61:*.gz=01;38;5;61:*.lz=01;38;5;61:*.xz=01;38;5;61:*.bz2=01;38;5;61:*.bz=01;38;5;61:*.tbz=01;38;5;61:*.tbz2=01;38;5;61:*.tz=01;38;5;61:*.deb=01;38;5;61:*.rpm=01;38;5;61:*.jar=01;38;5;61:*.rar=01;38;5;61:*.ace=01;38;5;61:*.zoo=01;38;5;61:*.cpio=01;38;5;61:*.7z=01;38;5;61:*.rz=01;38;5;61:*.apk=01;38;5;61:*.gem=01;38;5;61:*.jpg=00;38;5;136:*.JPG=00;38;5;136:*.jpeg=00;38;5;136:*.gif=00;38;5;136:*.bmp=00;38;5;136:*.pbm=00;38;5;136:*.pgm=00;38;5;136:*.ppm=00;38;5;136:*.tga=00;38;5;136:*.xbm=00;38;5;136:*.xpm=00;38;5;136:*.tif=00;38;5;136:*.tiff=00;38;5;136:*.png=00;38;5;136:*.svg=00;38;5;136:*.svgz=00;38;5;136:*.mng=00;38;5;136:*.pcx=00;38;5;136:*.dl=00;38;5;136:*.xcf=00;38;5;136:*.xwd=00;38;5;136:*.yuv=00;38;5;136:*.cgm=00;38;5;136:*.emf=00;38;5;136:*.eps=00;38;5;136:*.CR2=00;38;5;136:*.ico=00;38;5;136:*.tex=01;38;5;245:*.rdf=01;38;5;245:*.owl=01;38;5;245:*.n3=01;38;5;245:*.ttl=01;38;5;245:*.nt=01;38;5;245:*.torrent=01;38;5;245:*.xml=01;38;5;245:*Makefile=01;38;5;245:*Rakefile=01;38;5;245:*build.xml=01;38;5;245:*rc=01;38;5;245:*1=01;38;5;245:*.nfo=01;38;5;245:*README=01;38;5;245:*README.txt=01;38;5;245:*readme.txt=01;38;5;245:*.md=01;38;5;245:*README.markdown=01;38;5;245:*.ini=01;38;5;245:*.yml=01;38;5;245:*.cfg=01;38;5;245:*.conf=01;38;5;245:*.c=01;38;5;245:*.cpp=01;38;5;245:*.cc=01;38;5;245:*.log=00;38;5;240:*.bak=00;38;5;240:*.aux=00;38;5;240:*.lof=00;38;5;240:*.lol=00;38;5;240:*.lot=00;38;5;240:*.out=00;38;5;240:*.toc=00;38;5;240:*.bbl=00;38;5;240:*.blg=00;38;5;240:*~=00;38;5;240:*#=00;38;5;240:*.part=00;38;5;240:*.incomplete=00;38;5;240:*.swp=00;38;5;240:*.tmp=00;38;5;240:*.temp=00;38;5;240:*.o=00;38;5;240:*.pyc=00;38;5;240:*.class=00;38;5;240:*.cache=00;38;5;240:*.aac=00;38;5;166:*.au=00;38;5;166:*.flac=00;38;5;166:*.mid=00;38;5;166:*.midi=00;38;5;166:*.mka=00;38;5;166:*.mp3=00;38;5;166:*.mpc=00;38;5;166:*.ogg=00;38;5;166:*.ra=00;38;5;166:*.wav=00;38;5;166:*.m4a=00;38;5;166:*.axa=00;38;5;166:*.oga=00;38;5;166:*.spx=00;38;5;166:*.xspf=00;38;5;166:*.mov=01;38;5;166:*.mpg=01;38;5;166:*.mpeg=01;38;5;166:*.m2v=01;38;5;166:*.mkv=01;38;5;166:*.ogm=01;38;5;166:*.mp4=01;38;5;166:*.m4v=01;38;5;166:*.mp4v=01;38;5;166:*.vob=01;38;5;166:*.qt=01;38;5;166:*.nuv=01;38;5;166:*.wmv=01;38;5;166:*.asf=01;38;5;166:*.rm=01;38;5;166:*.rmvb=01;38;5;166:*.flc=01;38;5;166:*.avi=01;38;5;166:*.fli=01;38;5;166:*.flv=01;38;5;166:*.gl=01;38;5;166:*.m2ts=01;38;5;166:*.divx=01;38;5;166:*.webm=01;38;5;166:*.axv=01;38;5;166:*.anx=01;38;5;166:*.ogv=01;38;5;166:*.ogx=01;38;5;166:';export LS_COLORS
Command working from CLI but not from script
bash;scripting;colors
First you create the script containing your command and with /bin/bash as the interpreter; as follows :#!/bin/bashtest -r ~/.dircolors && eval $(dircolors -b ~/.dircolors) || eval $(dircolors -b)If you named your script for example setDirColors and you make it executable, you should execute it as follows :. ./setDirColorsNote the leading dot. It is not a typo. Calling your script without the leading dot will not work. Why is that so ? Your script set a value to LS_COLORS environment variable and export it ... to subprocesses of the script ! not to its parent ! To solve this classic pitfall, we use the leading dot which is a bash command to execute a script in current process. So the script can modify your current LS_COLORS environment variable.
_cs.50129
I saw here: http://www.cs.cmu.edu/~ninamf/ML11/lect0906.pdfIntuitively, if n is large but most features are irrelevant (i.e. target is sparse but examples are dense), then Winnow is better because adding irrelevant features increases L2(X) but not L(X). On the other hand, if the target is dense and examples are sparse, then Perceptron is better.Why adding irrelevant features increases L2(X) but not L(X)?
Winnow versus Perceptron - Why adding irrelevant features increases L2(X) but not L(X)?
machine learning;online algorithms;perceptron
null
_softwareengineering.223415
If I'm giving an interview coding question in Java, I can specify the most of the question just by giving a method signature. (Made-up example follows.)public class Table { public String identifier; public int seatCount;}public static List<String> tablesWithEnoughSeats(List<Table> tables, int minSeats)If the candidate prefers Python, how do I present the problem for them? The Python method signature doesn't specify the data type. Is there some standard Python way of doing this?If I look at Python coding challenges online, they tend to specify the requirements as taking certain input to produce certain output. I don't want the candidate to waste their time writing code to parse an input file. (My example has just String and int, but the actual interview problem might contain more complex data.) What's the best way to express the parameter constraints so that the candidate can implement the algorithm I'm interested in without doing a bunch of plumbing?
How to create a Python method prototype
python;prototyping
Mock your inputs. Say Assume that this array consists of integers or floats or whatever. You can also annotate things with comments.I'd write this in Python like so:class Table: #identifier: string, seat_count: int def __init__(self, identifier, seat_count): self.identifier = identifier self.seat_count = seat_countI'm prone to writing Python functionally so I'd instantiate a list of tables then call a function that checked each table to see if had enough seats or not. I'd probably use a filter to that. Could also do a list comprehension. The latter is more Pythonic.
_codereview.157156
I wrote this piece of code for a GUI i am making, which is a playlist interface. I was wondering if I could write all of this code out differently, but to the point where it functions exactly the same, as I am intrigued in learning different ways to write java to boost my flexibility and knowledge in the language. package java;import java.awt.*;import java.awt.event.*;import javax.swing.*;import static coursework.VideoData.setRating;public class UpdateVideos extends JFrame implements ActionListener { JTextField trackNo = new JTextField(2); JTextField newrate = new JTextField(2); TextArea content = new TextArea(6, 50); JButton apply = new JButton(Apply); public UpdateVideos() { setLayout(new BorderLayout()); setBounds(100, 100, 400, 200); setTitle(Check Videos); setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); JPanel top = new JPanel(); top.add(new JLabel(Enter Video Number:)); top.add(trackNo); top.add(new JLabel(Enter Rating:)); top.add(newrate); top.add(apply); apply.addActionListener(this); add(North, top); JPanel middle = new JPanel(); middle.add(content); add(Center, middle); setResizable(false); setVisible(true); } public void actionPerformed(ActionEvent e) { String key = trackNo.getText(); String name = VideoData.getName(key); Integer ratingnum; String newratenum; newratenum = newrate.getText(); ratingnum = Integer.parseInt(newratenum); if (e.getSource() == apply) { if (name == null) { content.setText(No such video number); } else { setRating(key,ratingnum); content.setText(name + - + VideoData.getDirector(key)); content.append(\nRating: + stars(VideoData.getRating(key))); content.append(\nPlay count: + VideoData.getPlayCount(key)); } } } private String stars(int rating) { String stars = ; for (int i = 0; i < rating; ++i) { stars += *; } return stars; }}
Video playlist interface in Swing
java;swing
At the danger of repeating myself (not to you, but generally regarding swing code):Don't learn swing. Swing has been EOL'd for over a year now and has been officially superseded by JavaFX. If you want to learn GUI programming for thick clients in java: Go with JavaFXSomebody has to have a tutorial that does this wrong ... UpdateVideos extends JFrame implements ActionListener is one of those lines that should make you shudder. It's a generally accepted wisdom that to write SOLID code, one should use Composition over Inheritance. This means that instead of saying UpdateVideos is a JFrame you should say: UpdateVideos has a JFrame.This is one of the things that every swing program seems to have and I find it terrifying: setVisible(true); in the constructor... This is a violation of two things. First: The principle of single responsibility (SRP), the S in SOLID. A constructor is responsible for getting the object it initializes into a usable, valid state. This does explicitly not entail making the JFrame inside the object (or the JFrame object itself) visible. Second: The principle of least surprise. Let's say you go to a coffee shop and order a coffee... would you expect the the coffee you get to pour itself down your throat? Sure you'll want to drink it sooner or later, but on your own terms. It's not the coffee's (or the JFrame's) responsibility to make sure that you drink (or show) it, but yours. After getting this out of the way, let's talk about your code: Aside from the two coding issues I already mentioned above your code is pretty clean. The only thing that really bothers me is how many magic numbers you use. There is a minor optimization in stars. Consider the following code:private String stars(int rating) { final char[] stars = new char[rating]; Arrays.fill(stars, '*'); return new String(stars);}This avoids the overhead of concatenating Strings and instead uses a char[] to basically build the string without an explicit for-loop. This is just a marginal benefit though and you might want to keep your method structure, but use a StringBuilder instead to increase performance.
_softwareengineering.316206
Is there a way to make Java interfaces only implementable by classes of a special type?So for instance, I have a class Foo and an interface Bar. Only subclasses of Foo should be able to implement Bar. Is this possible?(This would be useful if subclasses of Foo are the only classes that need to implement Bar. Other classes that don't really need to implement it simply can't.)Before you ask, I can't edit Foo to add the methods there, it's binary.
How to make interfaces usable for special classes only?
java;interfaces
null
_codereview.68691
It only does expressions with 2 operands yet, but I'm wondering if there are any ways I can improve this:# infix.rb: parse infix-operated math expressionsclass String def is_number? true if Float(self) rescue false endendclass InfixParser @operations = [ '/', '*', '+', '-' ] testString = '(24 + 6) / 10 * 3' shouldEqual = 9 def parseExpression(expr) #TODO: implement parsing of entire expressions end def self.parseChunk(chunk) chunk = chunk.gsub ' ', '' if not (chunk.include?('/') or chunk.include?('*') \ or chunk.include?('+') or chunk.include?('-')) puts error: no operations in chunk: #{chunk} exit end firstNumber = '' secondNumber = '' i = 0 currentChar = '' while not @operations.include? currentChar currentChar = chunk[i] if not currentChar.is_number? and not @operations.include? currentChar \ and currentChar != '.' puts error: non-numerical digit in chunk: #{currentChar} exit end firstNumber += currentChar i += 1 end firstNumber = firstNumber[0 .. -2] for c in i-1 .. chunk.length-1 if not chunk[c].is_number? and not @operations.include? currentChar \ and currentChar != '.' puts error: non-numerical digit in chunk: #{currentChar} exit end secondNumber += chunk[c] end secondNumber = secondNumber[1 .. secondNumber.length - 1] if chunk[i - 1] == '/' return Float(firstNumber) / Float(secondNumber) elsif chunk[i - 1] == '*' return Float(firstNumber) * Float(secondNumber) elsif chunk[i - 1] == '+' return Float(firstNumber) + Float(secondNumber) elsif chunk[i - 1] == '-' return Float(firstNumber) - Float(secondNumber) else puts error: invalid operator in chunk: #{chunk} end endend
Ruby infixed math parser
ruby;parsing;math expression eval
You've indicated that you prefer not to use regular expressions. In that case, you're still working too hard. In that case, you should look for a library function that does the job, such as the standard scanf library.require 'scanf'def eval_binary_expr(expr) l_operand, op, r_operand = expr.scanf('%f %c %f') if l_operand.nil? raise ArgumentError, Missing or invalid left operand end begin case op when '/' then l_operand / r_operand when '*' then l_operand * r_operand when '+' then l_operand + r_operand when '-' then l_operand - r_operand else raise ArgumentError, Missing or invalid operator end rescue TypeError raise ArgumentError, Missing or invalid right operand endendThis implementation is better than the original, in that it can handle negative operands and explicitly positive operands. It also examines the string from left to right, which makes it easier to understand its behaviour.
_softwareengineering.95520
We have Python middle-tier for our Web App . Now we need to render 3 different HTMLs...for older browsers (simple read-only interface)for HTML5 browsers (LOT more complex than older browsers)for mobile website (simple XHTML-MP)Now, we need to keep the Python middle-tier completely independent of any HTML -- just pure business logic.So, we think we should use a PHP layer on top of Python to generate these HTMLs. PHP would talk to Python via SOA.First -- is this a good idea? And if not, can you suggest a better design?Second, if this is a feasible design -- do you think PHP+Python is good (maintainable) mix. If not, how about replacing the PHP layer by yet another Python layer.Just remember that our middle-tier needs to be COMPLETELY isolated from any HTML thingy :)-- UPDATE --The reason we're inclined to using PHP is...PHP itself is just a template engine embedded into HTML -- and it is SO easy to generate complex HTML with it. On the other hand, Python is more of a general purpose language and generating HTML with it will require us to use a third party library which will entail maintenance/upgrade/security hassles. Generating HTML is a sort of raison d'tre for PHP.Secondly, Python support for Nginx is NOT as good as PHP.
is Python PHP polyglot a good design?
php;python
null
_unix.1566
I can't figure out how to get pseudostreaming on my Apache server (CENTOS 5.5 i686). I've read this article and these install instructions.I cannot install httpd-devel or mod_ssl via yum; I get the error package not found. One person mentioned that they think WHM/CPanel breaks yum.I have found some RPM packages:rpm.pbone.net/index.php3/stat/4/idpl/13945478/dir/centos_5/com/mod_ssl-2.2.3-43.el5.centos.x86_64.rpm.html rpm.pbone.net/index.php3/stat/4/idpl/13944425/dir/centos_5/com/httpd-devel-2.2.3-43.el5.centos.x86_64.rpm.html But as I am not a unix admin, I am unsure of where to go from here. Can someone point me in the right direction? (Please remember that I am very junior in linux administration.)
How to Update Apache to allow Pseudostreaming on CENTOS 5.5 & WHM
centos;apache httpd
null
_codereview.112541
It took some time to make Conway's Game of Life in HTML, CSS, JavaScript and jQuery. I'd like suggestions, criticisms, and discussions on how it can be done better.JSFiddle link/* * Conway's - Game of Life. * Any live cell with fewer than two live neighbours dies, as if caused by under-population. * Any live cell with two or three live neighbours lives on to the next generation. * Any live cell with more than three live neighbours dies, as if by over-population. * Any dead cell with exactly three live neighbours becomes a live cell, as if by reproduction. */'use strict';/* * Representation of each cell on the canvas. * row and col stores the location of the cell. * The alive property stores whether the cell is alive or dead. */function Cell(row, col) { var _this = this, $this = null, alive = false; this.activate = function () { alive = true; $this.addClass('alive'); }; this.deActivate = function () { alive = false; $this.removeClass('alive'); }; this.isAlive = function () { return alive; }; this.getRow = function () { return row; }; this.getCol = function () { return col; }; this.getJqueryElement = function () { return $this; }; // If $this is not yet defined, create a new HTML element. if (null === $this) { $this = $('<div>').addClass('conway-cell').data('cell', _this); } return this;}/** * The main logic of the game goes here. */function ConwayGame(selector, numRows, numCols) { var $parent = $(selector), _this = this, rows = numRows, cols = numCols, cells = [], lifeMap = [], intervalTime = 500, intervalId; this.getSpeed = function () { return intervalTime; }; // Initialize the list of cells required. Add the same to the HTML parent element. var initialize = function () { for (var i = 0; i < rows; i++) { cells[i] = []; var $row = $('<div>').addClass('conway-row'); for (var j = 0; j < cols; j++) { var cell = cells[i][j] = new Cell(i, j); var $cell = cell.getJqueryElement(); // Add click handler for the Cell. $cell.on('click', function (event) { var cellObj = $(this).data('cell'); if (cellObj.isAlive()) { cellObj.deActivate() } else { cellObj.activate(); } _this.reMap(); }); $row.append($cell); } // Add the HTML Row to the Parent element. $parent.append($row); } }; // Re-draw the Elements based on their status, if they are alive or not. this.reDraw = function () { for (var i = 0; i < rows; i++) { for (var j = 0; j < cols; j++) { var cell = cells[i][j]; cell.isAlive() ? cell.activate() : cell.deActivate(); } } }; // Get the count of immediate neighbors for the cell. this.getNeighborsCount = function (cell) { var neighbors = 0, row = cell.getRow(), col = cell.getCol(); // Top Left to Top Right if (cells[row - 1]) { if (cells[row - 1][col - 1] && cells[row - 1][col - 1].isAlive()) neighbors++; if (cells[row - 1][col] && cells[row - 1][col].isAlive()) neighbors++; if (cells[row - 1][col + 1] && cells[row - 1][col + 1].isAlive()) neighbors++; } // Middle Left to Middle Right. Ignore the current cell. if (cells[row][col - 1] && cells[row][col - 1].isAlive()) neighbors++; if (cells[row][col + 1] && cells[row][col + 1].isAlive()) neighbors++; // Bottom Left to Bottom Right. if (cells[row + 1]) { if (cells[row + 1][col - 1] && cells[row + 1][col - 1].isAlive()) neighbors++; if (cells[row + 1][col] && cells[row + 1][col].isAlive()) neighbors++; if (cells[row + 1][col + 1] && cells[row + 1][col + 1].isAlive()) neighbors++; } return neighbors; }; this.reMap = function () { for (var i = 0; i < rows; i++) { lifeMap[i] = []; for (var j = 0; j < cols; j++) { var cell = cells[i][j]; lifeMap[i][j] = _this.getNeighborsCount(cell); } } }; this.getNextLife = function () { for (var i = 0; i < rows; i++) { for (var j = 0; j < cols; j++) { var cell = cells[i][j]; var lifeValue = lifeMap[i][j]; if (cell.isAlive()) { if (lifeValue < 2 || lifeValue > 3) { cell.deActivate(); } } else { if (lifeValue === 3) { cell.activate(); } } } } _this.reMap(); }; this.next = function () { _this.getNextLife(); _this.reDraw(); }; this.play = function () { intervalId = setInterval(_this.next, intervalTime); }; this.pause = function () { clearInterval(intervalId); }; this.increaseSpeed = function () { if (intervalTime > 100) { intervalTime -= 100; } _this.pause(); _this.play(); }; this.decreaseSpeed = function () { if (intervalTime < 2000) { intervalTime += 100; } _this.pause(); _this.play(); }; if (cells.length === 0) { initialize(); } return this;}// Run as soon as the Document is Ready.$(function () { var game = new ConwayGame('.conway-game', 20, 20); $('#nextButton').on('click', function () { game.next(); }); $('#playButton').on('click', function () { game.play(); }); $('#pauseButton').on('click', function () { game.pause(); }); $('#speedUpButton').on('click', function () { game.increaseSpeed(); }); $('#slowDownButton').on('click', function () { game.decreaseSpeed(); });});.conway-game { display: table;}.conway-row { display: table-row;}.conway-cell { display: table-column; float: left; width: 12px; height: 12px; border: 1px solid #CCE8AF;}.alive { background-color: #7FC539;}.controls { margin-top: 10px;}.controls button { float: left;}<script src=https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js></script><div class=conway-game></div><div class=controls> <button id=playButton>Play</button> <button id=pauseButton>Pause</button> <button id=nextButton>Step</button> <button id=speedUpButton>Speed Up</button> <button id=slowDownButton>Slow Down</button></div>
JavaScript implementation of Conway's Game of Life
javascript;jquery;game of life
I cloned your code and created a website using the GitHub repo that I created with it so you can see some of the other changes that I make to the code as well. please feel free to fork it.In the initialize function of your ConwayGame class you used the length if then statement if (cellObj.isAlive()) { cellObj.deActivate()} else { cellObj.activate();}But then in the this.reDraw function you use a ternary statement for the same call, so I changed that right away. I know that these are reversed, but the ternary will operate in a similar fashion. It looks like thiscellObj.isAlive() ? cellObj.deActivate() : cellObj.activate();I also removed some of the comments because they were redundant when I looked at the line(s) of code that they were referring to.I also lightly touched the getNeightborscount function and changed it slightly, I pulled out rowAbove and rowBelow so that I could dry it up a little bit, but I was only able to pull these out so far, this is what it looks like currentlythis.getNeighborsCount = function (cell) { var neighbors = 0, row = cell.getRow(), col = cell.getCol(); var rowAbove = cells[row - 1]; var rowBelow = cells[row + 1]; //if (cells[row - 1]) { if (rowAbove) { if (rowAbove[col - 1] && rowAbove[col - 1].isAlive()) neighbors++; if (rowAbove[col] && rowAbove[col].isAlive()) neighbors++; if (rowAbove[col + 1] && rowAbove[col + 1].isAlive()) neighbors++; } if (cells[row][col - 1] && cells[row][col - 1].isAlive()) neighbors++; if (cells[row][col + 1] && cells[row][col + 1].isAlive()) neighbors++; //if (cells[row + 1]) { if (rowBelow) { if (rowBelow[col - 1] && rowBelow[col - 1].isAlive()) neighbors++; if (rowBelow[col] && rowBelow[col].isAlive()) neighbors++; if (rowBelow[col + 1] && rowBelow[col + 1].isAlive()) neighbors++; } return neighbors;};Let's move on to the this.getNextLife function.if (cell.isAlive()) { if (lifeValue < 2 || lifeValue > 3) { cell.deActivate(); cellsDestroyed++; }} else { if (lifeValue === 3) { cell.activate(); cellsCreated++; }}this looks a little clunky to me, at the very least that else statement should be an else if statement like thisif (cell.isAlive()) { if (lifeValue < 2 || lifeValue > 3) { cell.deActivate(); cellsDestroyed++; }} else if (lifeValue === 3) { cell.activate(); cellsCreated++;}I liked the way that you created classes and objects to handle the different functions of the Game itself so you could just call them on a click event.Edit:I found a bug in your code, you were counting surviving cells as newly created cells inside the getNextLife function. Here is how I fixed that.if (cell.isAlive()) { if (lifeValue < 2 || lifeValue > 3) { cell.deActivate(); cellsDestroyed++; } else if (lifeValue === 3) { cell.activate(); }} else if (lifeValue === 3){ cell.activate(); cellsCreated++; }}And really I don't think that you need to actually activate that cell or do anything to it if it is active and has lifeValue === 3so we could just write it like this insteadif (cell.isAlive() && (lifeValue < 2 || lifeValue > 3) { cell.deActivate(); cellsDestroyed++;} else if (lifeValue === 3){ cell.activate(); cellsCreated++;}All these updates are in the code @GitHub as well.
_unix.216381
I want to run two instances of dnscrypt client proxies, but I'm having trouble making them automatically start at boot. Here is what I tried:In rc.local, this is the first:/usr/local/sbin/dnscrypt-proxy -a 127.0.0.1:40 -u _dnscrypt-proxy -d -l /dev/null -R dnscrypt.eu-dkand the second:/usr/local/sbin/dnscrypt-proxy2 -a 127.0.0.1:41 -u _dnscrypt-proxy2 -d -l /dev/null -R dnscrypt.org-frI cd to /usr/local/sbin and did a cp dnscrypt-proxy dnscrypt-proxy2 and then when I rebooted I would get [ERROR] Unknown User : [dnscrypt-proxy2].Then I searched and saw this question then I manually edited /etc/passwd and added a new user carefully copying the default _dnscrypt-proxy user and changed the id, as now it has these 2 entries:_dnscrypt-proxy:*688:688:dnscrypt-proxy user:/var/empty:/sbin/nologin _dnscrypt-proxy2:*689:689:dnscrypt-proxy2 user:/var/empty:/sbin/nologin`And when I reboot, the Unknown User error still persists. A quick ls on the folder shows me I do have duplicated the folder. Ps aux shows me the daemon has not started. A Google search didn't help me so I turned to the Linux experts here. My OS is OpenBSD 5.7.
How to duplicate a daemon?
openbsd;daemon
First, here's the specific answer to your question of why the unknown user error persists: The error was in how you created the user. There are more files that need to be fixed than just /etc/passwd.The easiest way to properly create the user would be to simply remove that line from /etc/passwd and then run adduser -noconfig -shell -/sbin/nologin instead. (And when you edit /etc/passwd, use vipw instead of just vi /etc/passwd - see the man page for the explanation!)Second, you really don't need to create a second user. You can run the same program twice without having a copy of the program or a second user to run it under. What you need to do to run a second daemon with the same user and binary, but with different settings is simple:Copy the init script for the daemon to one with another name. (You've already done this.)Edit the new init script. Keep the same path to the binary and the same username. Change only the options that you want to be changed!Voil - you're ready to run!
_codereview.35858
This is a stored procedure that takes 5-30+ minutes to run depending on the parameter they select.It also has a nasty side effect of clogging down our SQL Server.SET NOCOUNT ON; DECLARE @clients TABLE (customer varchar(200)) IF (NULLIF(@startdate, '') IS NULL) set @startdate = getdate()-7 IF (NULLIF(@enddate, '') IS NULL) set @enddate = getdate() IF (ISNULL(@clientName,'') = 'ALL') INSERT INTO @clients SELECT customer FROM customer (NOLOCK) ELSE IF(ISNULL(@clientName,'') = 'Capital One') INSERT INTO @clients SELECT customer FROM customer (NOLOCK) WHERE customer in ('0000380','0000611','0000541','0000715') ELSE IF(ISNULL(@clientName,'') = 'PRA') INSERT INTO @clients SELECT customer FROM customer (NOLOCK) WHERE customer in ('0000411') ELSE IF(ISNULL(@clientName,'') = 'Midland') INSERT INTO @clients SELECT customer FROM customer (NOLOCK) WHERE customer in ('0000584') ELSE IF(ISNULL(@clientName,'') = 'Trak') INSERT INTO @clients SELECT customerid FROM fact (NOLOCK) WHERE customgroupid=25 ELSE IF(ISNULL(@clientName,'') = 'Hanna') INSERT INTO @clients SELECT customer FROM customer (NOLOCK) WHERE customer in ('0000644','0000647','0000648','0000665','0000697','0000726','0000773','0000803','0000804','0000814') ELSE INSERT INTO @clients SELECT customer FROM customer (NOLOCK) WHERE customer = @clientName -- Insert statements for procedure here select distinct m.number as FileNumber ,isnull(dbi.bankname, '') as Bank ,c.name as ClientName ,CONVERT(VARCHAR(10),m.received,101) as ReceivedByFirm ,'' as ChargeOffDate ,datediff(d, m.received, getdate()) as AgeOfDebt ,0 as DebtAmount ,case when d.lastname = '' then d.name else d.lastname end as DebtorLastName -- show d.name if debtor last name is blank ,CONVERT(VARCHAR(10),m.dob,101) as DateOfBirth ,dbo.stripnondigits(d.zipcode) as DebtorZipcode ,d.state as DebtorState ,d.homephone ,d.workphone ,'' as MobilePhone -- no mobile phone ,case when d.ssn != '' then 1 else 0 end as HasSSN ,case when pe.verified is not null then 1 else 0 end as Employed ,(select dbo.mmSddSyyyy(max(lr.DateProcessed)) from LetterRequest lr WHERE lr.DateProcessed>'' AND lr.DateRequested<GETDATE() AND Deleted=0 AND LetterCode in ('40029','50046','09997','09998','09999','10001','10002','10003','10004','10005','10006','10010','10011','10014','10015','50050','50041','50042','50001','50030','50040','50045','50060','50090','11001') AND lr.AccountID=m.number) as FirstLetterDate --Date letter sent to debtor by law firm ,(select min(created) from notes where number=m.number AND action like 'T%') as FirstCall ,(select count(created) from notes where number=m.number and created between @startdate and @enddate and action like 'T%') as TotalCalls ,(select case when count(created) > 0 then 1 else 0 end from notes where number=m.number and created between @startdate and @enddate and action = 'DT') as DebtorCalledFirm ,(select isnull(max(dbo.mmsddsyyyy(created)), '') from notes where number=m.number and created between @startdate and @enddate and action = 'DT') as DebtorCalledFirmDate ,case when m.status in ('PIF', 'SIF') then 1 when m.qlevel in (998,999) then 3 else 2 end as CollectionStatus ,m.desk as CollectorName ,isnull((select isnull(dbo.mmSddSyyyy(cc.DateFiled), '') from courtcases cc where cc.accountid = m.number and cc.DateFiled>'1900-01-01 00:00:00' and isnull(cc.casenumber,'')!='' and (m.current1+m.current2+m.current3+m.current4+m.current5+m.current6+m.current7+m.current8+m.current9+m.current10)>0), '') as SuitDate ,(select isnull(dbo.mmSddSyyyy(cc.ServiceDate), '') from courtcases cc where cc.accountid = m.number) as ServiceDate ,(select isnull(dbo.mmSddSyyyy(cc.JudgementDate), '') from courtcases cc where cc.accountid = m.number) as JudgmentDate ,isnull((select max(dbo.mmSddSyyyy(s.DateChanged)) from statushistory s inner join courtcases cc on s.accountid=cc.accountid inner join debtors d on d.number = cc.accountid where s.accountid=m.number and isnull(cc.JudgementDate,'')!='' and s.DateChanged >'1900-01-01 00:00:00' and s.newstatus in ('LNG','LXG','WGS','WGW','GIL','GNG') and isnull(cc.ServiceDate,'')!='' and isnull(d.jobname,'')!='' and s.id not in (select historyid from statuserror where accountnumber = m.number)), '') as GarnishmentDate ,getdate() as Today ,(select case when count(number) > 0 then 1 else 0 end from payhistory ph where ph.number = m.number and batchtype in ('PU', 'PC')) as PaymentMade ,isnull(datediff(d, m.received, getdate()) - (select datediff(d, min(ph.datepaid), getdate()) from payhistory ph where ph.number = m.number and batchtype in ('PU', 'PC')), '') as DaysElapsed ,case when m.status = 'PIF' then 'PIF' when m.status = 'SIF' then 'SIF' when m.status = 'PPA' then 'PPA' else '' end as PaymentMethod ,m.paid+m.paid1+m.paid2+m.paid3+m.paid4+m.paid5+m.paid6+m.paid7+m.paid8+m.paid9+m.paid10 as TotalPaid ,m.score as CollectionScore ,m.original as OriginalClaim ,isnull(datediff(d, m.received, m.chargeoffdate), '') as ChargeOff ,case when (isnull((select isnull(dbo.mmSddSyyyy(cc.DateFiled), '') from courtcases cc where cc.accountid = m.number and cc.DateFiled>'1900-01-01 00:00:00' and isnull(cc.casenumber,'')!='' and (m.current1+m.current2+m.current3+m.current4+m.current5+m.current6+m.current7+m.current8+m.current9+m.current10)>0), '')) = '' then 1 else 0 end as SuitFiled ,case when (select isnull(dbo.mmSddSyyyy(cc.JudgementDate), '') from courtcases cc where cc.accountid = m.number) = '' then 1 else 0 end as JudgmentObtained ,'' as JudgmentInOurFavor ,case when (isnull((select max(dbo.mmSddSyyyy(s.DateChanged)) from statushistory s inner join courtcases cc on s.accountid=cc.accountid inner join debtors d on d.number = cc.accountid where s.accountid=m.number and isnull(cc.JudgementDate,'')!='' and s.DateChanged >'1900-01-01 00:00:00' and s.newstatus in ('LNG','LXG','WGS','WGW','GIL','GNG') and isnull(cc.ServiceDate,'')!='' and isnull(d.jobname,'')!='' and s.id not in (select historyid from statuserror where accountnumber = m.number)), '')) = '' then 1 else 0 end as Garnishment from master m inner join customer c on c.customer = m.customer inner join debtors d on d.number = m.number inner join jm_people p on p.accountid = m.number left outer join jm_peopleemployment pe on pe.pid = p.pid left outer join debtorbankinfo dbi on dbi.acctid = m.number where m.customer IN (SELECT customer from @clients) order by m.number
Stored procedure to run a credit-card debt query
sql;sql server;time limit exceeded
performance review of SQL code without knowing the cardinality of the data, and the indexes used, is a real challenge, but, I would recommend that you try two things:first, try make @customer table a top-level item in the Join:from @customer csubinner join master m on csub.customer = m.customerinner join customer c on csub.customer = c.customer.....The other item that concerns me is that you use the DISTINCT keyword. This automatically implies a temp-table and a sort. This could be a 'killer' for this query because it has to compute and save all the select-value calculations. From what I can tell, there is no reason why you should get duplicate data anyway.The 'order-by' may be possible to solve without a temp table (perhaps the query-plan can be tweaked to query off the master table in number order using an index (is the data clustered by number?), but I would consider removing it (the order-by) as well, unless you really need the data sorted by that.
_cstheory.21962
Is there an approach to graph isomorphism considering that we are already given a partial isomorphism ?In particular, it would be interesting to have conditions on this partial isomorphism that makes the problem polynomial.This question arises from automata theory, where one approach to testing equivalence of two NFAs on alphabet $A$ is to compute their syntactic semigroups $M_1,M_2$ (of exponential size) together with functions $h_1:A\to M_1$, $h_2: A\to M_2$. Testing semigroup isomorphism is hard in the general case, but here we can do it polynomially, because $h_1,h_2$ already give us a partial isomorphism for a set of generators, which is enough. For graphs, an obvious sufficent condition for such a partial isomorphism to make the problem polynomial would be containing a covering set (in the sense each edge contains a vertex in it) . Maybe there are more subtle conditions that would still work ?
graph isomorphism given a partial isomorphism
graph isomorphism
null
_unix.310226
I would like to map the Windows/Meta key in my vimperatorrc & vimrc, including Meta-key bindings for tab movement: move to previous tabnnoremap <M-h> gT move to next tabnnoremap <M-l> gtUnfortunately neither Vimperator nor Vim accepts these bindings. Although they do not complain, the bindings simply do not work.According to this tutorial: How to map keys in Vim, <M-...> should map the meta (windows) key?!Any ideas?System setup:I am using Vim and Vimperator on Manjaro (Arch Linux Fork) within KDE. Thus, Vim runs in Yakuake (KDE's terminal manager/multiplexer) and Vimperator in FireFox 48.Sidenote: Vim shows the same behavior when launched in a normal terminal, outside of Yakuake.
Vim & Vimperator: Map Windows/Meta key?
vim;keyboard shortcuts
In Vim, meta is the same as alt. Cp. :help meta:<M-...> alt-key or meta-key *meta* *alt* *<M-*<A-...> same as <M-...> *<A-*In Pentadactyl, this supposedly works (cp. :help key-notation):<A->: The alt key.<M->: The meta key, windows key, or command key.But at least for me (on Ubuntu with Gnome classic), meta mappings don't work at all (probably because they don't arrive in the browser at all).
_unix.56391
If I have a virtualenv activated when I do something like sudo apt-get install python2.7-devshould I expect different results than if I did it outside the virtual env?Limited theory says no, but I'm not sure I'm aware of everything I should be.
When I am in VirtualEnv and do apt-get install, is there any difference?
apt;python
virtualenv is Python-specific, so no: apt-get will operate in your whole system. Thus there will be no different results.
_webmaster.14731
I try to setup SSL on my server for only one web site (I have few there using IIS7). I bought an SSL certificate, installed it but when I come to bind I don't have to option to specify the host name. From reading some posts here I understood I need a distinct IP address.I didn't purchase a wildcard certificate, I got staging.mydomain.com.My question is:My server has a distinct IP, can I use it although I have other sites there but they don't need ssl?If I do need to buy dedicated IP. What does it involve?
SSL Certificate and IP Binding
iis7;security certificate
In answer to your question:1 . My server has a distinct IP, can I use it although I have other sites there but they don't need ssl?There is really no mucking about when it comes to SSL, your site will need its own IP address for a single domain SSL. There are various hacks and bodges I've seen people do over the years, they all end in tears.2 . If I do need to buy dedicated IP. What does it involve?If you're self hosting your server in an office/home at the end of a DSL or cable service then you need to ask your provider for a range of static IP addresses. If your server is rented from a hoster (RackSpace, Orcs etc) or it's your own hardware in a data-centre then you'd need to ask the hoster or IP transit provider for more IP addresses.As to cost, this can vary from one-off payments of around $50 for a /29 (6 usuable addresses) to annual renting of an IP address of perhaps $10 per IP/per year. It will vary enormously from provider to provider.One thing to note is that if you change DSL/Cable/Hosting/Transit provider - you can't take the IP addresses allocated with you. They are part of their larger allocation from a regional internet registry and owned by them.
_cogsci.13019
I've come across these terminologiesthreshold symptoms and sub-threshold symptomsin one of the papers in psychology where delayed reactions are introduced:Empirical studies that have mapped PTSD symptoms over time in fact observed what appear to be delayed elevations in the direction of threshold symptoms...However, I don't have any ideas what those words are all about.
What are threshold symptoms and sub-threshold symptoms?
clinical psychology;psychology;ptsd
null
_softwareengineering.307928
If I am assigned a bug, I sometimes check version control to see when it was introduced. Should I notify the developer that introduced the bug, even if I already fixed it? The advantage is that it could help learning but the disadvantage is it could seem like criticism
Should I notify my colleagues when I find a bug in their code?
bug
null
_unix.119970
I'm trying to intercept the clone system call so that I could print user ID and process ID before the actual system call executes. I am using get_user_id()->uid to access user ID in kernel module but it returns user ID in kuid_t type, which I can not cast to int. Is there any other way to do this? I've read about using getuid() (from unistd.h) in other forums but interestingly the compiler recognizes the first use of this function as an implicit declaration.
User ID in kernel module
linux kernel;kernel modules;uid
That struct is defined in include/linux/uidgid.h. The only thing it contains is a val member of type uid_t, which is what the userspace getuid returns (an unsigned int on Linux, follow the headers by browsing via Linux Cross Reference for example).Either access it directly from your kuid_t variable, or use __kuid_val from that same header.
_softwareengineering.343378
Say I have two views (Table View for example) that I'd like them to do different stuff; each loads different data but behaviors are similar for most par except what happens when a cell tapped for instance. One shows a list of entries, another a list of users, another a list of comments, etc. I can write one subclass of UITableViewControler for all with a flag variable to distinguish the logic or a separate sub class per each view controller. I am trying to figure out what is best. I know smaller blocks are easier to debug, etc. But yet again, it's sort of repeating code to have multiple of the same class boilerplate. What would a good approach here?
Which one is more efficient; a subclass of UITableViewController for multiple purposes or multiple sub classes each for a purpose?
design patterns;object oriented;ios;objective c;swift language
null
_webmaster.105057
Ports are blocked by firewall causing me to have no connection on my s5, unless I use a VPN. Please help. Desperate !!
Blocked Ports 5228, 5229, 5230 and many more
firewall
null
_cs.76234
I am a TA for an introductory CS course, and one question given to students was how to use BFS to determine the diameter of a graph. The students were told they wouldn't be graded for efficiency, so the expected answer was a brute force algorithm where they ran BFS from every node to every other node and returned the maximum distance from these BFS runs. The students were provided with a BFS method they could reference in their pseudocode which took as an input a node and returned two mappings: one from each node in the graph to its distance from the start node (called distmap), and one from each node to its 'parent node' along the shortest path from the input node (called parentmap). One student wrote the following algorithm:1. Choice an arbitrary node from the graph and run BFS from it.2. Create a set Temp of all the nodes that are not values in parentmap (ie nodes which don't lie upon any shortest paths)3. Initialize max_dist to 04. For each node n in Temp: 5. Run BFS from n 6. For each value d in distmap: 7. IF d > max_dist THEN set max_dist equal to d8. RETURN max_distI believe this answer is correct, but I am unable to prove it. Can someone prove why it works or provide a counterexample?
Correctness of Algorithm for Computing Diameter of a Graph
graphs;graph theory;graph traversal
null
_unix.261040
I am logged into a (normal) user, but when I go su : password my normal promt goes into showing me this instead of what it should. how to I fix this? 10:15 AM (~) $ suPassword: \033[1;31m \@ \033[1;33m(\033[1;34m\W\033[1;33m) \033[1;31m$ \033[0mI am using this case statment to change prompts depending on which term is fired up. which_term(){ term=$(ps -p $(ps -p $$ -o ppid=) -o args=); found=0; case $term in *terminator*) found=1 export PS1=\@ \[\e[34;43m\]\w\[\e[m\]\\$ if [ -f /usr/bin/screenfetch ]; then screenfetch; fi ;; *terminology*) found=1 # echo terminology export PS1= \[\e[31m\]%\[\e[35m\]\u\[\e[m\]\[\e[36m\]@\[\e[m\]\[\e[35m\]\h\[\e[m\] \[\e[32m\]\T\[\e[m\] \[\e[36m\]\w\[\e[m\]\[\e[31m\] >>$\[\e[m\]\`nonzero_return\` if [ -f /usr/bin/screenfetch ]; then screenfetch; fi ;; urxvt*) found=1 # echo rxvt #PS1='%\u@\h \@ \W >>\$' export PS1=\[\e[33m\]%\[\e[m\]\[\e[31m\]\u\[\e[m\]\[\e[33m\]@\[\e[m\]\[\e[31m\]\h\[\e[m\]:\[\e[36m\]\@\[\e[m\]\[\e[33m\]\w\[\e[m\]\[\e[31m\] >>\[\e[m\]\[\e[33m\]\\$\[\e[m\] #export PS1='\033[1;31m \033[1;33m(\033[1;34m\W\033[1;33m)\@\033[1;31m\$ \033[0m' ;; Eterm*) found=1 export PS1=\d \@ Scooby-Doo\w\\$ # if [ -f /usr/bin/screenfetch ]; then screenfetch -t; fi ;; aterm*) found=1 export PS1=\d \@ Aterm\w\\$ ;; roxterm*) found=1 export PS1='% \@ \u@\h \W>>\$' ;; mrxvt*) found=1 export PS1=\[\e[31m\]\T\[\e[m\]\[\e[33m\]@\[\e[m\]\[\e[31m\]\u\[\e[m\]\[\e[34m\]\h\[\e[m\]\[\e[35;42m\]\W\[\e[m\] ;; ## Try and guess for any others *) export PS1='\033[1;31m \@ \033[1;33m(\033[1;34m\W\033[1;33m) \033[1;31m\$ \033[0m' if [ -f /usr/bin/screenfetch ]; then screenfetch -t; fi ;; esac ## If none of the version arguments worked, try and get the ## package version [ $found -eq 0 ] && echo $term $(dpkg -l $term | awk '/^ii/{print $3}') } which_term
how to get terminal to show root prompt in su
terminal;bashrc
null
_unix.121435
How do I add a bootloader to a Linux ISO?When I isoinfo -d -i ... I do not see the bootloader on one of the ISO's that I have; but on another ISO there is a bootloader.
How to add bootloader to ISO? Or, make ISO bootable?
linux;boot loader;iso
null
_unix.379589
I have a file fooap.p and I am using sed command to get the output like fooap.echo fooap.p | sed s/\.\p//g but the output I am getting is just foo.Am I missing something?
replacing special characters using sed command
sed
null
_vi.3615
If I have the folowing file:XX:YY:ZZ foobar: some textXX:YY:ZZ foobar: some other texta text breaking the patternXX:YY:ZZ foobar: some more textAnd I want to operate on the differents parts XX:YY:ZZ foobar: of the lines. When I am on the first line I can select the text that I want with, for example, v3f:. Now when I am on the second or on the last line how can I select this same text without type once again v3f:?I insist on the fact that I need to select the texts sequentially and not all the occurences at the same time.I know the command gv which allows to re-select the last selected area but in my case it will select the 16 first characters of the first line which is not what I want.To sum it up How can I execute again the last selection command?(Also I wasn't sure about the tags I should use for this question don't hesitate to edit/suggest the right ones to use)
How to select with the same movement but on a different line
cursor movement;search
You could simply create a quick mapping::nnoremap <key> 0v3f:Or use a macro recording:qq0v3f:qthen:@qHere is another method, lifted from the experimental part of my config:function! GetVisualSelection() let old_reg = @v normal! gvvy let raw_search = @v let @v = old_reg return substitute(escape(raw_search, '\/.*$^~[]'), \n, '\\n', g)endfunctionnnoremap <key> *``gn<C-g>inoremap <key> <C-o>gn<C-g>xnoremap <key> <Esc>:let @/ = GetVisualSelection()<CR>gn<C-g>Select your text with v3f:.Press <key> to enter insert mode.Edit the selection directly.Press <key> again to jump to the next match.GOTO 3--- edit ---GetVisualSelection() returns a representation of the selected text suitable for use as a search pattern (escaped slashes and so on).The normal mode mapping jumps to the next occurrence of the word under the cursor (with *), comes back (with ``), selects the last search (with gn, here it is the word under the cursor) and switches to select mode (<C->g) to allow us to type right away.The insert mode mapping temporarily jumps out of insert mode (with <C-o>) to jump to and select the next occurrence (with gn) and switches to select mode.The visual mode mapping has the same function as the normal mode mapping but it is implemented differently: it goes out of visual mode (with <Esc>), places a prepared representation of the selected text in the search register (with :let @/ = GetVisualSelection()<CR>), jumps to and select the next occurrence (with gn) and switches to select mode (with <C-g>.--- endedit ---
_cstheory.21100
It is a common belief that $\mathbf{P}\subsetneq\mathbf{PSPACE}$, thus (most likely) there are problems that are harder for time than for space. But is there a problem in $\mathbf{P}$ with a poly-space lower bound (say for multi tape TM), i.e. is there a space-hard problem in $\mathbf{P}$?Similarly, is there a problem in $\mathbf{P}$ with a good non-deterministic time lower bound? Is there a problem in $\mathbf{NP}$ with poly-space lower bound? ...
Problems of similar complexity for different measures
cc.complexity theory;complexity classes
The answer to the first question is that we don't know, because we don't know whether $\mathbf P=\mathbf L$, so it could be that all $\mathbf P$ problems use only logarithmic space.For the second one, most reasonable problems need at least linear time to read the input, even for non-deterministic machines, so it does not make a lot of sense to say polynomial non-deterministic lower bound, or you need to make your question more precise.Finally, the last question is like the first one: it could be that $\mathbf{NL}=\mathbf{NP}$, in which case such a problem wouldn't exist, we don't know...
_softwareengineering.166530
Possible Duplicate:Best practices for retrofitting legacy code with automated tests I've been working on a project in Flex for three years now without unit testing. The simple reason for that is the fact that I just didn't realize the importance of unit testing when being at the beginning of studies at university. Now my attitude towards testing changed completely and therefore I want to introduce it to the existing project (about 20000LOC).In order to do it, there are two approaches to choose from:1) Discard the existing codebase and start from scratch with TDD2) Write the tests and try to make them pass by changing the existing codeWell, I would appreciate not having to write everything from scratch but I think by doing this, the design would be much better.What would be your approach?
Introduce unit testing when codebase is already available
unit testing;tdd;refactoring
Rewriting from scratch just so you can have automated tests is silly - you have a codebase that (mostly) works, and you probably can test it (just not automatically). A rewrite, even with all the tests in the world, introduces extra risk, and it always takes longer than expected. So don't do that.Writing tests to achieve 100% coverage in one go is also silly, because it means you are halting on-going development to implement something which doesn't add any value yet. In most situations, this is unacceptable. Further, writing tests for code that already works and doesn't need changing has little benefit other than verifying that it does indeed work (but if it's running in production, you better be pretty sure about that already).The best way to go, IMO, is to add tests as you go. That is, for every change you make, apply the following steps:See whether existing tests sufficiently describe the current functionality.If necessary, add tests to capture the current functionality of that particular part / module / class / function / ... Verify that they pass.Refactor existing code if necessary.Modify the tests to reflect the intended new behavior.Modify the code to make the tests pass.Refactor.Steps 4 through 6 are just basic TDD; the only addition is that you retroactively add tests as needed before you start the actual TDD cycle.If you follow this procedure, and the tests you add in step 2 are sufficient, the codebase will gradually move towards full test coverage.Of course, if you are going to rewrite anyway, for different reasons, then going TDD right from the start is probably a good idea.
_vi.13194
When writing block quotes Markdown, I want to make vim act the same way it does with comment leaders and automatically start new lines with the '>'. I also want to be able to format text this way with gq. How can I do this? I set my formatoptions to fo+=tacqw.
Automatically add '>' at beginning of line following one starting with '>' when writing Markdown
formatting;filetype markdown
It turns out vim handles block quotes in Markdown pretty much the way I asked for since at least version 7.4. It loads ftplugin/markdown.vim which sets '>' as a comment leader. It also adds the t flag to formatoptions and removes the r and o flags. That means if you write until the text is longer than textwidth, you get a new line that starts with >. But if you just press enter or add a new line with o or O you won't get the '>' on the new line. So if you want this functionality you have to override the file type plugin. You can do that by creating the file .vim/after/ftplugin/markdown.vim and adding set formatoptions+=ro to it.My situation was that I had some paragraphs in a Markdown file that I wanted to turn into blockquotes by adding '>' at the start of every line. The paragraphs were already formatted so there were hard line breaks in them. I added '>' to the start of the first line and expected vim to make the whole paragraph commented if I used gq over it. Obviously that's not what gq does when you have a hard line break after what it recognizes as a comment. If it did, code written after a comment when programming would itself be commented out. We can solve the problem if we join the lines of the paragraph by pressing [count]J where [count] is the number of lines to be joined. Then gq will format the paragraph as we want. If you have the a flag in formatoptions it's not necessary to use gq because the text is automatically reformatted.
_reverseengineering.6323
Here is my question: How can the Windows 7, 8, etc. boot process work?The first piece of code loaded from the volume boot sector of the OS is bootmgr.exe. But here's why this doesn't make sense:An exe is a portable executable file, which is composed of metadata that the OS (Windows) parses. There's no way the boot manager can be a PE file when mostly the entire OS needs to be loaded to parse PEs, namely the loader, memory management services, system threads for VM, device drivers, etc.So how can the first program be a PE? My assumption is that it can't, or else it wouldn't make sense (the CPU does not parse PEs unless Windows' loader software tells it to).So basically, on the lowest-level, the Windows boot process is false/misdealing info?
Windows boot process doesn't make sense!
assembly;hardware;binary;binary format
null
_cs.46867
is there any difference between transition systems and finite automata? Is it that transition systems consist of both NFA (nondeterministic finite automata)and DFA (deterministic finite automata)?
What is the difference (if any) between transition systems and finite automata?
terminology;automata;finite automata;transition systems
Yes, did you try wikipedia?To quote the second paragraph [in transition systems]:The set of states is not necessarily finite, or even countable.The set of transitions is not necessarily finite, or even countable.No start state or final states are given.
_webapps.98703
A B C D E-----------------------------------foo bar test foobar-----------------------------------10 13 3 1 bar-----------------------------------9 3 3 9 ?I am trying to identify the highest number of results in my survey and have it appear in column E. However, I can't figure out how make a tie appear in column E. It doesn't matter whether it takes multiple columns to get what I want. Here is the formula I used for the first row of data.=INDEX(A$1:D$1, 1, MATCH(MAX(A2:D2), A2:D2, 0))
Use MATCH but with 2 identical values in Sheets
google spreadsheets
null
_unix.24378
When I type something which is neither a zsh builtin and no such executable is found from $PATH, zsh just reports an error. Instead, I would like zsh to check if a named directory exists with that name and cd into it. I tried defining command_not_found_handler() function but it didn't work as it forks a sub-shell to execute that function and hence directory change is not reflected in the actual shell.Is it something that is already possible with some settings or a new (useful?) feature?
How to cd into the named directory if command not found?
zsh
null
_unix.79067
I work on a server software that is targeted for RHEL/CentOS and is currently distributed via a standard RPM file. What brings me here is that it includes a downloadable client engine that users can get to by going through the main web UI.So this is what I have:Downloadable agent is still something my company maintains but it has a separate release cycle.Each new RPM version is typically associated with a specific agent version (typically also newer, but potentially could be the same)When users upgrade the server, they may wish to continue using the same agentAgent install is currently packaged with the RPM, so when the server is upgraded, older version of the agent is removed from the system.Apparently (4) is not desirable so what we want is to keep all agent versions that have every been installed even as the server component is being upgraded.One possible solution that might work is to put agent into its own RPM that has agent version number in the name and that the main RPM would require as its dependency. So when the product is installed, rpm -qa would show:<product>-1.0.0<product>-agent-install-1.0.5-1.0 (might be a better way to format the name)And when the server is updated, you would see:<product>-2.0.0<product>-agent-install-1.0.5-1.0<product>-agent-install-1.2.0-1.0As I'm not by any stretch of imagination a Linux expert, I'd like to know if the strategy I outlined above is...a possible solution (i.e. I'm not missing something obvious that would kill the whole idea)an acceptable practice or a hackIs there a cleaner way that you would do instead? For example, I could have each server install, simply copy off the agent installer into a separate directory and since the other directory is not managed by the RPM, it'll stick around and not get deleted. But would that be better?
Best way to release an RPM that includes an independently version module
rhel;software installation;rpm
null
_unix.297262
After edited the /etc/security/limits.conf file to set the nofile parameter to unlimited, server got hanged . Can't login in via ssh. Tried to take console, issue with console. Will reboot of the VM will solve the login issue ?
Can't login after editing /etc/security/limits.conf
linux;login;virtual machine;system recovery
null
_codereview.90760
I thought of a program where you move a square with the arrow keys. I created it and asked a question about it on Stack Overflow.I copied the last code block of the accepted answer and tried to understand it. I think I do now. Now I wanted to add something that would check if the square would move off the screen. I added that myself as seen here:Code inside Square class that replaces the move method of the copied code:public void move(Direction dir) { if(!(x + step * dir.getIncrX() > GamePanel.getWIDTH() - w) && !(x + step * dir.getIncrX() < 0)) x += step * dir.getIncrX(); if(!(y + step * dir.getIncrY() > GamePanel.getHEIGHT() - h) && !(y + step * dir.getIncrY() < 0)) y += step * dir.getIncrY();}To achieve this I had to make the constants WIDTH and HEIGHT static and create getters for them. Is the way I created this collision detection good practise? and should the getters for the constants be called getWidth and getHeight istead of getWIDTH and GetHEIGHT?Full code:import java.awt.*;import javax.swing.*;import java.awt.event.*;import java.util.EnumMap;import java.util.HashMap;import java.util.Map;public class GamePanel extends JPanel { private static final int ANIMATION_DELAY = 15; private static final int HEIGHT = 500; private static final int WIDTH = 500; private Square square; private EnumMap<Direction, Boolean> dirMap = new EnumMap<>(Direction.class); private Map<Integer, Direction> keyToDir = new HashMap<>(); public GamePanel() { for (Direction dir : Direction.values()) { dirMap.put(dir, false); } keyToDir.put(KeyEvent.VK_UP, Direction.UP); keyToDir.put(KeyEvent.VK_DOWN, Direction.DOWN); keyToDir.put(KeyEvent.VK_LEFT, Direction.LEFT); keyToDir.put(KeyEvent.VK_RIGHT, Direction.RIGHT); setKeyBindings(); setBackground(Color.white); setPreferredSize(new Dimension(getWIDTH(), getHEIGHT())); setFocusable(true); square = new Square(); Timer animationTimer; animationTimer = new Timer(ANIMATION_DELAY, new AnimationListener()); animationTimer.start(); square.setStep(5); } public static int getHEIGHT() { return HEIGHT; } public static int getWIDTH() { return WIDTH; } private void setKeyBindings() { int condition = WHEN_IN_FOCUSED_WINDOW; final InputMap inputMap = getInputMap(condition); final ActionMap actionMap = getActionMap(); boolean[] keyPressed = { true, false }; for (Integer keyCode : keyToDir.keySet()) { Direction dir = keyToDir.get(keyCode); for (boolean onKeyPress : keyPressed) { boolean onKeyRelease = !onKeyPress; KeyStroke keyStroke = KeyStroke.getKeyStroke(keyCode, 0, onKeyRelease); Object key = keyStroke.toString(); inputMap.put(keyStroke, key); actionMap.put(key, new KeyBindingsAction(dir, onKeyPress)); } } } public void paintComponent(Graphics g) { super.paintComponent(g); square.display(g); } private class AnimationListener implements ActionListener { @Override public void actionPerformed(ActionEvent e) { boolean repaint = false; for (Direction dir : Direction.values()) { if (dirMap.get(dir)) { square.move(dir); repaint = true; } } if (repaint) repaint(); } } private class KeyBindingsAction extends AbstractAction { private Direction dir; boolean pressed; public KeyBindingsAction(Direction dir, boolean pressed) { this.dir = dir; this.pressed = pressed; } @Override public void actionPerformed(ActionEvent evt) { dirMap.put(dir, pressed); } } private static void createAndShowGUI() { GamePanel gamePanel = new GamePanel(); JFrame frame = new JFrame(GamePanel); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.getContentPane().add(gamePanel); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); gamePanel.requestFocusInWindow(); } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { createAndShowGUI(); } }); }}enum Direction { UP(0, -1), DOWN(0, 1), LEFT(-1, 0), RIGHT(1, 0); private int incrX; private int incrY; Direction(int incrX, int incrY) { this.incrX = incrX; this.incrY = incrY; } public int getIncrX() { return incrX; } public int getIncrY() { return incrY; }}class Square { private int x = 0; private int y = 0; private int w = 20; private int h = w; private int step = 1; private Color color = Color.red; public void display(Graphics g) { Graphics2D g2d = (Graphics2D) g.create(); g2d.setColor(color); g2d.fillRect(x, y, w, h); g2d.dispose(); } public void setStep(int step) { this.step = step; } public void move(Direction dir) { if(!(x + step * dir.getIncrX() > GamePanel.getWIDTH() - w) && !(x + step * dir.getIncrX() < 0)) x += step * dir.getIncrX(); if(!(y + step * dir.getIncrY() > GamePanel.getHEIGHT() - h) && !(y + step * dir.getIncrY() < 0)) y += step * dir.getIncrY(); }}
Check for collision with side of screen
java;swing;collision
Change the visibility of WIDTH and HEIGHT to public, so you can call them by GamePanel.WIDTH and GamePanel.HEIGHT. Because for static final variables you never create Getters!And you should change your code like this to improve it's performance:public void move(Direction dir) { int newX = x + step * dir.getIncrX(), newY = y + step * dir.getIncrY(); if (!(newX > GamePanel.WIDTH - w) && !(newX < 0)) x = newX; if (!(newY > GamePanel.HEIGHT - h) && !(newY < 0)) y = newY;}
_softwareengineering.311876
I have been working in embedded devices business more than 5 years as a software engineer. Most of the times our hardware manufacturers provide a Software Development Kit for their reference boards. They are mostly Linux embedded devices. The problem is most of the times we find the management interfaces (Web UI, CLI, SNMP ...) are tightly coupled with the database that stores persistent device configuration and also the interfaces carry out each one in their own all the operations to apply the new setting to the system. For instance when the user updates firewall state via Web UI the web server is performing itself the C system() function calls using iptables rules as argument. It makes us very unproductive because:We can not reuse cohesive components in new products. Specifications for new products are becoming more demanding and embedded system are costly to develop.Management interfaces are not consistent and code is repeated among them. As the code is tightly coupled and the abstraction is bad, the same goes for the tasks. It is difficult to parallelize tasks if the developer of a new functionality should know about the web server or the web server maintainer should know about a functionality implementation details.We can not test components but the whole system.Sometimes the management interfaces call database API to store new setting and after that they call the same function which reads new functionality setting from database and apply the new setting in the system. I think it is not yet a good solution but I would like to hear opinions about this design. Now we are trying to break up the software in responsible components we can reuse in new products. For instance we would like to use current embedded device services in new products, and also we would like to have user interfaces we can easily adapt for a new specification.As software engineer I am aware about the consequences of bad abstraction, low cohesion and poor encapsulation in software design, but I don't have a good background in design patterns. This is our plan:Built a set of C functions for device services that can be called from the user interfaces, exposing an interface that hides all the possible implementation details from the use of the service. There will be functions to change the system time, to manage the GPIOs, to change the firewall state...This services APIs will take care about the persistence of its data by using the API of the persistence layer. The user interfaces will retrieve and set new settings using this API services set of functions. Each API of a service will expose a x_initialize() function so when system boots up a startup manager application can call this function for each service. This functions will retrieve settings for the service from database and apply them into the system by calling the other functions of its own service API. I don't like very much the point 4 above because it looks pretty much like the situation we have now where the user interfaces store new setting in database and call a big function nobody know what this function does until it is seen the implementation details (and looking implementation detail of a function is a bad symptom for me).I am looking for information about design patterns to reuse and separate concerns as persistent layer, user interface and the business or domain objects logic (I am not very sure I use well concepts as domain objects). I would like an explanation with concrete examples I can better understand.
How to uncouple and reuse persistence logic, user interface logic and business logic amongs embedded software projects
design patterns;database design;linux;embedded systems;coupling
What your looking for is an MVC-style framework that runs on you target operating system. https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controllerThe pattern is very old, has many variants and frameworks are constantly being evolved and new ones developed. So, all I would venture to do is generalize a bit: the model in MVC has your business/domain-logic-protected and persisted data (meaning it shouldn't let you store something incorrect), the view handles rendering of various model elements to the ui, and the controller handles binding and forwarding of commands from ui controls to the model (requests to make changes) and/or view (e.g commands asking to change views). A nice MVC framework can make it easier to work at a higher level, so you won't find yourself repeating as much plumbing.As I mentioned, the MVC pattern is rather old, and was originally developed to support the development of UI-based desktop applications. As such, it did not directly account for persistence the way we think of it today (which is that all changes are automatically persisted; instead it expected the user to open files and save them later). It is sensible to separate the model into persistence oriented part and a the business logic oriented part (that ensures no dangling references, for example, and enforces any other requirements of the data model).(Also, since you are using a database, you might look into ORM to help with persistence and mapping of persistence to objects and back again.)You're definitely asking the right questions, so keep looking for those common abstractions that you can use across your various projects. I love it when the code just reads nice because it is high level and uses the right abstractions, which take care of themselves without having often having to dive deeper. Nicely layered code is so much easier to work with. The idea is that you create layers by introducing a higher level API and then when a layer above uses it, that layer does not reach around or bypass the next lower layer to talk to an even lower layer. When you get that you can manage a lot more lines of code than when everything is, perhaps, modular, but at the same level.I'm not very up-to-date on linux MVC or ORM frameworks, but I think this is where you should be looking.
_unix.11172
Transmission is intermittently hanging on my NAS. If I send SIGTERM, it doesn't disappear from the process list and a <defunct> label appears next to it. If I send a SIGKILL, it still doesn't disappear and I can't terminate the parent because the parent is init. The only way I can get rid of the process and restart Transmission is to reboot.I realize the best thing I can do is try and fix Transmission (and I've tried), but I'm a novice at compiling and I wanted to make sure my torrents finished before I start messing around with it.
How can I kill a process whose parent is init?
kill;signals;process management;init;zombie process
You cannot kill a <defunct> (zombie) process as it is already dead. The only reason why the system keeps zombie processes is to keep the exit status for the parent to collect. If the parent does not collect the exit status then the zombie processes will stay around forever. The only way to get rid of those zombie processes are by killing the parent. If the parent is init then you can only reboot.http://en.wikipedia.org/wiki/Zombie_process
_vi.9344
I have the file /path/a.md which has many sections as follows:# abcthis this the content of section abc# defthis this the content of section abc## defgthis this the content of subsection defg of defAnd in an other file /path/b.md I have the the following:I want to switch to def section by this link [section def in a.md](./a.md#def), yeh the file name and the section name are separated by # and this kind of link is also possible:[subsection defg in a.md](./a.md##defg)
Open markdown filename under cursor like gf, and jump to the section?
key bindings;multiple files;filetype markdown
This function is not thoroughly tested but it should provide a good enough bootstrap for your own experiments.In ~/.vim/after/ftplugin/markdown.vim:function! s:MDGoToSection() let raw_filename = expand('<cfile>') let arg = substitute(raw_filename, '\([^#]*\)\(#\{1,6\}\)\([^#]*\)', '+\/\2\\\\s\3 \1', 'g') execute edit argendfunctionnnoremap <buffer> <key> :call <SID>MDGoToSection()<CR>ExplanationThe filename under the cursor is split into three groups:\([^#]*\)......................... everything before the first # \(#\{1,6\}\)............. 1 to 6 # \([^#]*\).... everything after #######and reordered into a proper argument for :edit:+\/\2\\\\s\3 \1which should split ./foo.md##bar into ./foo.md, ##, and bar, and finally pass +/##\\sbar ./foo.md to :edit::edit +/##\\sbar ./foo.md
_webapps.27059
I'm considering setting up a Facebook account but have some concerns about privacy. Specifically, I don't want Facebook to provide the name of Friend A (say) to Friend B if I haven't agreed to this myself.I'm aware that I can hide my list of friends on Facebook. The question is whether such friends will turn up on other peoples' People You May Know list.For example, if I am friends with two people, A and B, and have hidden my friend list to everyone but myself, will person B see person A on the People You May Know list, or vice versa?Please respond only if you're 100% sure about this.
How to keep my friends (100%) private on Facebook
facebook;friends
null
_unix.248600
I have a script that reads a file of about 3GB and sends it through a pipeline involving a very small number of replacements in a very small part of the file. To accomplish this with minimal overhead, the script specifies a small known range within which to make the replacements using sed '/begin/,/end/'. I would like to add another couple replacements in another small, known, regex-delimited range in the same file. If I pipe through sed again, that introduces unnecessary overhead, and won't scale up nicely.Is there a way to specify two ranges between patterns if I know the order in which they will appear in the file, such that the file only needs to be read once?Something like 'sed '/begin1/,/end1/ ... /begin2/,/end2/' is what I have in mind.The sed manual states An address range can be specified by specifying two addresses separated by a comma (,).But it doesn't mention specifying sets of two addresses each.
sed: multiple ranges between patterns, with one pass
sed;performance;patterns
You don't need to know which range appears first in the file. You can write the obvious:#/bin/sed -f/begin1/,/end1/{# commands specific to range 1}/begin2/,/end2/{# commands specific to range 2}and it will Just Work.Sed always makes a single pass through its inputs, reading each line, processing it through the commands you've given it, and then writing (or not, as appropriate). You can prove this by executing sed in a pipeline (piped input is not seekable, so multi-pass operation is not possible).
_unix.115031
I've installed program trickle that allow to throttle the net for specified command like:trickle -u10 -d10 <COMMAND>How to add bash completion for all binaries to trickle command?
How to add all binaries to bash tab completion for some command?
bash;autocomplete
Do you have, and load, the file /etc/bash_complete or an equivalent directory? It defines a bunch of completions and extension facilities beyond what's built into bash. If you have access to them, you can probably just usecomplete -o filenames -F _command trickleIt will complete the first argument of trickle as a command, and will then try to apply appropriate completion rules for subsequent arguments. But it depends on the shell function _command, which is defined in the above file (in my Debian system, at least). YMMV on other Linux distributions, and the file doesn't seem to be present in Darwin (OS X 10.8).
_unix.312655
I am trying to convert a file from utf-8 to ms-ansi.I use iconv -f UTF8 -t MS-ANSI// < data.txtbut get iconv: illegal input sequence at position 171359when looking into this dd if=data.txt of=error.txt bs=1 count=10 skip=171359I get this: hexdump -C error.txt 00000000 ef bb bf 38 3a 6e 61 09 38 3a |...8:na.8:| 0000000ais the file not utf-8, and if not, what should I use instead with iconv?
Why can't I convert a UTF-8 to MS-ANSI using iconv?
text processing;character encoding
null
_softwareengineering.205600
I am a single developer working on a large system. I was recently informed that there may be an opportunity to recruit another developer or maybe two. I have incorporated source control into my approach using Subverison and Tortoise SVN.I was talking to another developer who I used to work with recently and he reminded me about the concept of a compilation tool chain and specifically nightly builds for unit testing. I have two questions:Is it good practice for all software development teams to use unit testing and nightly builds? Is there any criteria that identifies teams that are more suitable than others for nightly builds.How do developers identify areas suitable for unit testing? I assume that you look at the use cases. I assume that these use cases could include different processing methods e.g. users interacting with a web application or a batch processing job that runs via a scheduled task each night.
Source control and compilation tool chain
version control;builds
null
_webmaster.48238
I have a client who recently did a re-design on his website. The designer did not put any effort in keeping the same URL or do any redirects. I've made a list of the old URLs, what I want to do now is check if these URLs have links that pass any juice.Can anyone tell me if it's possible to see if the old URLs that are linking to 404 carry any backlinks and how to do that?
Check old urls for backlinks - same domain new design and urls
seo;search engines;301 redirect;backlinks;anchor
Google Webmaster Tools is probably your easiest bet here. In the 'Crawl Errors' section it will list 404s it found crawling your site, along with the pages that link to them. It may not be a completely exhaustive list but it will have the majority of them.
_unix.89887
I'm developing a utility that needs to do low-level random access of disks (read individual sectors). In Linux I accomplish this by accessing the corresponding block device (e.g. /dev/sda). However, I've just installed FreeBSD, and I noticed that it doesn't have block devices. Instead, disks appear as character devices, which don't allow random seeking.Is there a way to accomplish this in FreeBSD? (i.e. low-level random access)
Low-level disk access in FreeBSD
freebsd;block device
Disk character devices are equally if no more low level than block devices and are hopefully randomly seekable. One major difference between block devices and raw ones is the former are buffered while the latter are synchronous. That's the reason why FreeBSD dropped disk block devices.
_unix.29247
I'm on a macbook running Lion. In Terminal I'm connected to my schools server with ssh. I navigated to a folder on the server and have a file I want to copy to my local machine, but I don't know what the IP address of my local machine is. How can I get it? I'm in the folder on the server, and I want to copy read.txt onto my local machine's hard drive. I've tried scp ./read.txt [my computer name].local/newRead.txt but it doesn't work.
How can I get the address of my local machine?
ssh;ip;remote;file copy
You don't need to know your own host's IP address in order to copy files to it. Simply use scp to copy the file from the remote host:$ scp [email protected]:path/to/read.txt ~/path/to/newRead.txtIf you want to copy to your local host from your remote host, get your own IP address with ifconfig and issue the following:$ scp path/to/read.txt [email protected]:path/to/newRead.txtwhere 1.2.3.4 is your local IP address. A convenient way to extract a host's IP address is using this function:ipaddr() { (awk '{print $2}' <(ifconfig eth0 | grep 'inet ')); }where eth0 is your network interface. Stick it in ~/.bash_profile in order to run it as a regular command - ipaddr.
_cstheory.19969
I heard that there exist two styles to define an evaluation context: outside-in and inside-out. Can someone give the definitions? Why are they so named (inside-out and outside-in)? What is the difference? Some examples would be appreciated.
Evaluation contexts: outside-in vs inside-out
pl.programming languages;lambda calculus;functional programming;operational semantics
null
_codereview.146674
I went about this the way I have because Selenium is slow and inconvenient (opens browser) and I was unable to find the href attribute in the link element using BeautifulSoup. Html included below. On the downside, this appears to only ever find 25 images.#! python3# Saves photos to file from flickr.com using specified search termimport bs4import loggingimport osimport reimport requestsimport shutilimport sysimport timedef find_link(element): Finds link using a regular expression link_regex = re.compile(r//c\d+.staticflickr.com/\d+/\d+/\w+\.jpg) # dictionary of element attributes element_attr_dict = element.attrs # get list of element attribute values wherein image link lies attr_list = [element_attr_dict[key] for key in element_attr_dict.keys()] attr_string = # link exists within a string list element for element in attr_list: if type(element) == str: attr_string += element match = link_regex.search(attr_string) if match: link = https: + match.group() else: link = None return linkdef main(): Downloads specified type/number of 'flickr' images to folder Takes three command line arguments: filename, search_term, number_ images. Saves images to folder. Number of images saved based upon number requested by user or number found during search. Whichever is lower. Arguments: search_term -- search image site using this term number_images -- maximum number of images to save to folder try: search_term, number_images = sys.argv[1:] number_images = int(number_images) except ValueError: print(Something went wrong. Command line input must be of \format: 'filename searchterm numberimages') return links = [] # make folder to store photos and name using search term html_path = rC:\Users\Dave\Desktop\2016Coding\AutomateBoring\11 + \ r-WebScraping\flickrhtml.txt path = \ rC:\Users\Dave\Desktop\2016Coding\AutomateBoring\11-WebScraping + \ r\gimages\requests folder_path = os.path.join(path, search_term) if os.path.exists(folder_path): shutil.rmtree(folder_path) os.makedirs(folder_path) print(Finding photos...) # get links to photos res = requests.get(https://www.flickr.com/search/?text= + search_term) res.raise_for_status() soup = bs4.BeautifulSoup(res.text, html.parser) found_elems = soup.select(.photo-list-photo-view) # incase number found images < requested number_save_images = min(number_images, len(found_elems)) print(Found {} images.format(number_save_images)) for found_elem in found_elems[:number_save_images]: link = find_link(found_elem) links.append(link) # write images to file print(Writing images to folder...) for image_link in links: basename = os.path.basename(image_link) save_file_name = os.path.join(folder_path, basename) res = requests.get(image_link) res.raise_for_status() with open(save_file_name, wb) as f: for chunk in res.iter_content(100000): f.write(chunk) print(Images saved at: {}.format(folder_path)) print(*****Done*****)if __name__ == __main__: main()
Image hosting site image downloader using requests and BeautifulSoup
python;web scraping;beautifulsoup
According to PEP8 standard library import should be first.Function find_link(element):The docstring of the function find_link should probably say something about the argument type.Why is the argument element (and not element_attributes) when it looks like all you use is element.attrs?The list comprehension could be written as: attr_list = list(element_attr_dict.values()) But, you don't need it at all. You can simply write for element in attr_dict.values().To summarize, you can delete most lines in the beginning. Instead start withdef find_link(element_attributes): link_regex = re.compile(r//c\d+.staticflickr.com/\d+/\d+/\w+\.jpg) attr_string = for element in element_attributes.values(): ...As for the main function:Investigate argparse.Use logging instead of print.Split the main function to sub-functions. At least saving an image from a link should probably be one.The for loop where you append a link to a list can be expressed as a list comprehension.I hope that helps!
_softwareengineering.305088
Suppose I have a sorted array which contains n integers.How do I find subset of size k such that the minimum distance between all pairs of integers in the subset is maximized, I mean they are at maximal distance.example: array a[]={1,2,6,7,10} and k=3,subset = {1,6,10}, the minimum distance is 4 between 10 and 6.Wrong subsets:{1,7,10} , minimum distance is 3{1,2,6} , minimum distance is 1 My first thought was to get all the combinations in the size of k, then calculate the distance of each one. But the time complexity would be O(n!), and the interviewer doesn't like it. Dynamic Programming is the hint he gave me, but I still have no idea.He suggested that I can start from a[0], find a[0]+x=Y also in the array... and then Y+x and so on k-1 times, also kth element will be a[n-1], but I couldn't get him. I don't know why there must be such a x, like in the example above, the correct answer is {1,6,10}, the distance between 1 and 6 is 5, and it's 4 between 6 and 10, then what should x be?
How to find a subset of size k such that the minimum distance between values is maximum
java;dynamic programming
null
_codereview.134558
I'm in the process of adapting the simple thread pool described here to my application. I'm new to concurrency in Ruby, but here is what I have so far:queue = Queue.newdata.each { |datum| queue.push datum }mutex = Mutex.newresults = []threads = (1..8).map do Thread.new do abort_on_exception = true while datum = queue.pop(true) rescue exit next unless datum.process? result = process(datum) mutex.synchronize { results << result } end endendthreads.map(&:join)Do you see any obvious mistakes and/or ways this code could be improved, cleaned up or made more Ruby-ish?I'm setting abort_on_exception = true because I'd like the entire processing effort to halt immediately should one datum fails to process correctly.
Ruby thread pool implementation
ruby;multithreading;ruby on rails;concurrency
null
_webapps.6895
I need a light weight web based note keeping application. The app should be runnable on Android/ iphone.I need such an app because I find that I do grocery shopping once in a week, and by the time I get to do shopping, I forget what I want to buy already.So I need such an app so that I can jot down my necessities in my daily life, and view the list when I'm doing the shopping.Does such an app already available?Gmail task is a good choice. But it is a bit too general. Edit: Thanks for all the recommendation! But I would prefer the one with OpenID support even though it has less features, rather than the one without with more features.
Light Weight Web Based Note Keeping Application
notes
null
_unix.62939
I'm developing a little application for Gnome, Unity and KDE desktops. I want the application icons to be fully theme aware.Now, I'm including the icons on the application directory on /usr/lib/my-application/ as SVG, and I'm loading them with the full path. I suppose this is fine as the start point, but I want to integrate them on the system better.My motivation: I don't want to break the Humanity and Humanity-Dark themes --very worried about the Indicator panel looks. How do I provide Humanity and Humanity-dark icons? How do I know the current theme? Should I ask for it?I'm using mostly bash and python.
Where place own application icons? How to get the current theme icons?
bash;gnome;kde;icons;freedesktop
null
_codereview.131491
Today I had to write a small tool to help me send HTTP requests in bulk. Rabbit was overloading my server, so I decided to change my consumers to buffer the contents of the request, before sending. After changing my API, I did this:#include <amqpcpp.h>#include <amqpcpp/libev.h>#include <ev.h>#include <cpr/cpr.h>typedef std::unordered_map<std::string, std::ostringstream> HttpBuffer;const char* RabbitQueue = getenv(RABBIT_NAME);char QueueAddress[128];int main(){ sprintf(QueueAddress, amqp://%s:%s, getenv(RABBIT_HOST), getenv(RABBIT_PORT)); int MaxThreads = std::thread::hardware_concurrency(); std::vector<std::thread> threads; for (int i = 0; i < MaxThreads; i++) { threads.push_back(std::thread(RabbitThread)); } for (std::thread &thread : threads) { thread.join(); } threads.clear();}void RabbitThread(){ struct ev_loop *loop = ev_loop_new(0); AMQP::LibEvHandler handler(loop); AMQP::TcpConnection connection(&handler, AMQP::Address(QueueAddress)); AMQP::TcpChannel channel(&connection); AMQP::MessageCallback onMessage = [&channel](const AMQP::Message &message, uint64_t deliveryTag, bool redelivered) { HttpBuffer[message.replyTo()] << message.message().c_str() << ,; if (HttpBuffer[message.replyTo()].tellp() < 300000) { channel.ack(deliveryTag); return; } cpr::PostCallback(handle_response, cpr::Url{http://localhost:8888}, cpr::Body{HttpBuffer[message.replyTo()].str()}); HttpBuffer[message.replyTo()].str(); channel.ack(deliveryTag); }; channel.declareQueue(RabbitQueue); channel.bindQueue(default, RabbitQueue, default); channel.consume(RabbitQueue).onReceived(onMessage); ev_run(loop); ev_loop_destroy(loop);}What do you guys think? How can I improve this one?
Bulk HTTP request queue consumer
c++;c++11;rabbitmq
null
_unix.227177
How would a single administrator go about locking himself out of a file for 24 hours?By lock I mean prevent access.I have removed the 'rules' placed on the original post, as it is clear that the strategies are dependent on what is being locked.
How would an administrator of a system prevent himself access to a file for 24 hours?
linux;bash;files;permissions
null
_unix.330637
I am trying to install the GitLab community package on a Debian Stretch system, but one of its dependencies, redis-server, fails to install when starting the service using systemd.Complete log:$ sudo dpkg --configure redis-serverSetting up redis-server (3:3.2.5-4) ...Job for redis-server.service failed because the control process exited with error code.See systemctl status redis-server.service and journalctl -xe for details.invoke-rc.d: initscript redis-server, action start failed. redis-server.service - Advanced key-value store Loaded: loaded (/lib/systemd/system/redis-server.service; enabled; vendor preset: enabled) Active: activating (auto-restart) (Result: exit-code) since Thu 2016-12-15 15:00:17 UTC; 31ms ago Docs: http://redis.io/documentation, man:redis-server(1) Process: 8764 ExecStart=/usr/bin/redis-server /etc/redis/redis.conf (code=exited, status=227/NO_NEW_PRIVILEGES) Process: 8761 ExecStartPre=/bin/run-parts --verbose /etc/redis/redis-server.pre-up.d (code=exited, status=227/NO_NEW_PRIVILEGES) Main PID: 24283 (code=exited, status=227/NO_NEW_PRIVILEGES)Dec 15 15:00:17 Serverdatorn-Debian systemd[1]: redis-server.service: Unit entered failed state.Dec 15 15:00:17 Serverdatorn-Debian systemd[1]: redis-server.service: Failed with result 'exit-code'.dpkg: error processing package redis-server (--configure): subprocess installed post-installation script returned error exit status 1Errors were encountered while processing: redis-serverStarting redis-server by running the executable manually works perfectly:$ sudo /usr/bin/redis-server /etc/redis/redis.conf$ sudo tail /var/log/redis/redis-server.log...* The server is now ready to accept connections on port 6379If there is any other information you want me to provide, please tell me.EDIT:I tried setting NoNewPrivileges to both yes and no in the redis.service file, reloading and starting it again, but no luck, same error. I did find that running journalctl -xe showed another message that might be helpful: redis-server.service: Failed at step NO_NEW_PRIVILEGES spawning /usr/bin/redis-server: Invalid argument
How to resolve systemd (code=exited, status=227/NO_NEW_PRIVILEGES)?
debian;systemd;redis
I would guess you are running into this result of the systemd NoNewPrivileges= directive. Assuming that the redis-server package generally works Ubuntu 16.04 systems, this suggests that your system may custom global settings for NoNewPrivileges= or a related directive that's causing Redis to fail to start.Read the docs linked about about NoNewPrivileges= and the related directives, then search in your /etc/systemd/ directory to see if any of those values have been customized on your system. If not, confirm that the redis package you are installing is indeed supported on the operating system version you are installing it on.
_softwareengineering.171316
I have some contextthen I can do:with context.getError(Object): ErrorHolderholder.addError(error)ORcontext.setError(Object, error)setError will probably have this implementation:context.getError(Object).addError(error)what approach should I choose and why?
two ways of doing the same thing, what is preferred?
java;design patterns
I would definitely go with the second method. Why?Well it seems to be the simplest answer. In the first instance it will require two calls everytime you need to add or get an error from your context. There is another alternative, provided that you are providing your Object classes and they are not generated by some 3rd party lib.You can add an ErrorCollection property to the base class of your data objects that keeps errors. That way when your object moves around the errors are linked with it. That way you will haveobject.addError()object.getError(index)This is cleaner because you are not maintaining objects and a relation of objects to their errors.
_cseducators.2520
It is said that metaphors can do more harm than good, and I agree that other methods should be developed, like the notional machine idea. However, computer science is not like anything else, because it is a constructed reality. It therefore seems like the best way to teach it is to show students how a new concept is similar to or related to things they are already familiar with.What do you do to work around the the problems of using metaphors to teach, such as students' cultural divergence (and therefore ability to understand the metaphor)?
Avoiding difficulties when teaching with metaphors
teaching analogy;classroom management;engagement
I think you pretty much need to use metaphor/analogy initially. The students need a hook to get called into the game. You make a good point, though, about finding metaphors that work with the generation of students you are teaching. It isn't so much a problem if you teach the same things (same sort of things even) over many years as you can evolve along with your students. One Pedagogical Pattern is Consistent Metaphor, which suggests that the parts of the thing being taught needs to map onto the parts or elements of the metaphor. This may be easiest if you use a Physical Analogy (another pedagogical pattern) as the parts of the analogy object are often pretty obvious. But without metaphor you are pretty much limited to technical detail, which can be hard to visualize and map to a mental model. However, every metaphor has limits. You need to make the students aware of the limits. This is how A is like B. This is how A is NOT like B. Equally important, or students can go astray.
_unix.17956
Suppose I run the following commands:export STR=abcdef.ghijkl.mnopqr.stuvwy.logecho $STR | sed 's/\.[^.]*$//'I am getting the following result:abcdef.ghijkl.mnopqr.stuvwyPlease help me understand the above result.
Facing problem with Regex Inside Sed Command
sed
Your sed pattern \.[^.]*$ has only one match to the original string: .log.Details:\. match only a dot character.[^.] matches any character different from .[^.]* matches any sequence of characters different from .$ matches the end of line.So here the final .log is the only match (.stuvwy.log is not a match because it contains an internal dot). sed will substitute this by the empty string as requested by the command s/\.[^.]*$//. Therefore you end up with:abcdef.ghijkl.mnopqr.stuvwy
_codereview.59037
Is there a simple way to combine the functions of this Powershell script? It would be nice to have it file to one output file instead of several output files. GET-DATEWRITE-EVENTLOG -logname Application -Source BLERG -EventID 1000 -entrytype Information -message START CBM_PARSE.ps1 -category 1############################################################################################################################################$SA_Location = E:\Users\jsweeton\Documents\SITES\CBM\Storage Analysis\CBM-FS3SET-LOCATION $SA_Location$filenames = @(GET-CHILDITEM $SA_Location -recurse -include *.csv)$regex = '^([^-]+-[^-]+)-([A-Z])-(\d{4})(\d\d)(\d\d).+'# $PIPE = ,$PIPE = $([char]0x2C)# $SLASH = \$SLASH = $([char]0x5C)# $DSLASH = \$DSLASH = $([char]0x5C)$([char]0x5C)foreach ($file in $filenames) {$outfile = $file + .out$ReplaceString = ($file | Split-Path -leaf) -replace $regex,'$1|$3-$4-$5|$2:'((GET-CONTENT $file| Out-String).Substring(7)) | FOREACH-OBJECT -Verbose { $_ -replace \\,\\ ` -replace $PIPE,| ` -replace E:,$ReplaceString ` } | SET-CONTENT $outfile}GET-DATEWRITE-EVENTLOG -logname Application -Source BLERG -EventID 1002 -entrytype Information -message END Parsing -category 1ECHO END PARSE############################################################################################################################################GET-DATEWRITE-EVENTLOG -logname Application -Source BLERG -EventID 1000 -entrytype Information -message START CBM-FS3 -category 1GET-CONTENT (GET-CHILDITEM E:\Users\jsweeton\Documents\SITES\CBM\Storage Analysis\CBM-FS3\*.out) | out-file -encoding UTF8 C:\Users\jsweeton\Documents\SITES\CBM\Storage Analysis\CBM-FS3\CBM-FS3.txtWRITE-EVENTLOG -logname Application -Source BLERG -EventID 1002 -entrytype Information -message END CBM-FS3 -category 1ECHO END CBM-FS3<#GET-DATEWRITE-EVENTLOG -logname Application -Source BLERG -EventID 1000 -entrytype Information -message START CBM-FS56 -category 1GET-CONTENT (GET-CHILDITEM C:\Users\jsweeton\Documents\SITES\CBM\Storage Analysis\CBM-FS56\*.out) | out-file -encoding UTF8 C:\Users\jsweeton\Documents\SITES\CBM\Storage Analysis\CBM-FS04\CBM-FS04.txtWRITE-EVENTLOG -logname Application -Source BLERG -EventID 1002 -entrytype Information -message END CBM-FS56 -category 1ECHO END CBM-FS56#>GET-DATEWRITE-EVENTLOG -logname Application -Source BLERG -EventID 1002 -entrytype Information -message END CBM_PARSE.ps1 -category 1ECHO END END############################################################################################################################################
Adding file name information to CSV file columns
csv;powershell
null
_softwareengineering.348295
I have been tasked with writing unit tests for an existing application. After finishing my first file, I have 717 lines of test code for 419 lines of original code.Is this ratio going to become unmanageable as we increase our code coverage? My understanding of unit testing was to test each method in the class to ensure that every method worked as expected. However, in the pull request my tech lead noted that I should focus on higher level testing. He suggested testing 4-5 use cases that are most commonly used with the class in question, rather than exhaustively testing each function.I trust my tech lead's comment. He has more experience than I do, and he has better instincts when it comes to designing software. But how does a multi-person team write tests for such an ambiguous standard; that is, how do I know my peers and I share the same idea for most common use cases?To me, 100% unit test coverage is a lofty goal, but even if we only reached 50%, we would know that 100% of that 50% was covered. Otherwise, writing tests for part of each file leaves a lot of room to cheat.
Is there such a thing as having too many unit tests?
unit testing;tdd
Yes, with 100% coverage you will write some tests you don't need. Unfortunately, the only reliable way to determine which tests you don't need is to write all of them, then wait 10 years or so to see which ones never failed.Maintaining a lot of tests is not usually problematic. Many teams have automated integration and system tests on top of 100% unit test coverage.However, you are not in a test maintenance phase, you are playing catch up. It's a lot better to have 100% of your classes at 50% test coverage than 50% of your classes at 100% test coverage, and your lead seems to be trying to get you to allocate your time accordingly. After you have that baseline, then the next step is usually pushing for 100% in files that are changed going forward.
_unix.293299
I have an eGPU setup of nVidia GT710 via Express Card. When linux boots up my main laptop screen works but the secondary screen doesn't work.I am using opensource drivers as both cards require different proprietary drivers. Both the devices are recognized.*-display description: VGA compatible controller product: GT218M [NVS 3100M] vendor: NVIDIA Corporation physical id: 0 bus info: pci@0000:01:00.0 version: a2 width: 64 bits clock: 33MHz capabilities: pm msi pciexpress vga_controller bus_master cap_list rom configuration: driver=nvidia latency=0 resources: irq:32 memory:d2000000-d2ffffff memory:c0000000-cfffffff memory:d0000000-d1ffffff ioport:7000(size=128) memory:d3000000-d307ffff*-display description: VGA compatible controller product: NVIDIA Corporation vendor: NVIDIA Corporation physical id: 0 bus info: pci@0000:06:00.0 version: a1 width: 64 bits clock: 33MHz capabilities: pm msi pciexpress vga_controller bus_master cap_list rom configuration: driver=nvidia latency=0 resources: irq:33 memory:e2000000-e2ffffff memory:d8000000-dfffffff memory:e0000000-e1ffffff ioport:4000(size=128) memory:e3000000-e307ffffWhen I tried to boot via UBUNTU Usb both the displays work. Would someone be able to help me out? I like Deepin's look and feel more than any other distro.I previously installed nVidia Drivers (to no avail) and I have nVidia X Server Settings app. It lists both of my GPUs.
eGPU Setup on Deepin 15.2 (Ubuntu Based)
drivers;nvidia;graphics
null
_unix.303547
I am trying to execute headless firefox on the remote machine(running Ubuntu 16.04) through Selenium via SSH. However, this gives me a Error: GDK_BACKEND does not match available displays error. My host machine runs Windows. I do not want to see the graphical output. It is just being used for selenium testing.I am using X Virtual Frame Buffer to act as a dummy driver:Xvfb :10 -screen 0 1024x768x16 &I also have exported the DISPLAY environment variable with the value of 10 for this specific case.Where am I going wrong?EDIT: When I simply run sudo firefox in my commandline over SSH after running xvbf, no errors are thrown. Errors are only thrown when running firefox through selenium.More Details:-I am calling firefox through selenium. The exact error that the selenium standalone server gives is:-17:52:55.218 INFO - Executing: [new session: Capabilities [{browserName=firefox, platform=ANY, firefox_profile=UEsDBBQAAAAAAJuOD0nf9RXUMgAAA...}]])17:52:55.230 INFO - Creating a new session for Capabilities [{browserName=firefox, platform=ANY, firefox_profile=UEsDBBQAAAAAAJuOD0nf9RXUMgAAA...}]org.openqa.selenium.firefox.NotConnectedException: Unable to connect to host 127.0.0.1 on port 7055 after 45000 ms. Firefox console output:Error: GDK_BACKEND does not match available displays
Error when executing headless firefox through Selenium
ubuntu;x11;firefox;headless;selenium
Apparently this is caused because of incompatibility between Firefox 48 and Selenium(selenium extension is not signed in firefox 48, and firefox 48 only runs signed extensions). I just used chrome, as my use-case was not extremely browser-specific.
_codereview.128256
I created a simple command line calculator, and then after some reading I made a few tweaks and then remade it with a friends idea to make it more simpler. I'm wondering if this can be more optimized or if any part of the code can be done better?I recently started learning Java and wanted for this first project of mine to end up the best possible written, so I can start learning on what is a good code.One of the things that was changed over time was the use of the Scanner.Firstly I had it create a new one on each iteration of kalkulator(); but that was obviously a unnecessary waste.Then I had a static scanner static Scanner scanMe = new Scanner(System.in); but somewhere I read It was better to pass it as an argument, because something that doesn't belong anywhere doesn't have place in a good code unless it is really necessary.Here is what I ended up with so far:Main Method:public class SimpleCalculator {public static void main(String[] args) { Scanner scanMe = new Scanner(System.in); kalkulator(scanMe);}Helper Methods:static double scanDouble(Scanner scan){ while (!scan.hasNextDouble()){ System.out.println(Invalid number! Please try again.); scan.nextLine(); } return scan.nextDouble();}static String scanOperator(Scanner scan){ String In = scan.next(); while (!(In.equals(+) || In.equals(-) || In.equals(*) || In.equals(/) || In.equals(end))) { System.out.println(Invalid operator! Please select either: +,-,*,/); In = scan.next(); } return In;}The Main Method: public static void kalkulator(Scanner scan) { double prviB = 0, drugiB = 0, rezultat = 0; String operator; System.out.println(Enter the 1st number: ); prviB = scanDouble(scan); System.out.println(Enter the 2nd number: ); drugiB = scanDouble(scan); System.out.println(Select an operator: (+,-,*,/) , or type 'end' for termination: ); operator = scanOperator(scan); switch (operator) { case +: rezultat = prviB + drugiB; break; case -: rezultat = prviB - drugiB; break; case *: rezultat = prviB * drugiB; break; case /: rezultat = prviB / drugiB; break; case end: System.out.println(Terminated.); scan.close(); System.exit(0); break; default: break; } System.out.println(Result: + rezultat); System.out.println(); kalkulator(scan);}
A simple command-line calculator
java;beginner;calculator
null
_codereview.172184
I am trying to make general class to find mode. I am looking for some general feedback on how I can improve the structure and efficiency of my code.package analysis.statistic;import java.util.Arrays;import java.util.Comparator;import java.util.HashMap;import java.util.Map;import java.util.Objects;public class Mode {/** * Return objects which appears most often. * * @return Map<object,countAppears> most appears objects. */@SuppressWarnings(unchecked)public static <T> Map<T, Integer> mode(T... objects) { Objects.requireNonNull(objects, objects must not be null); if (objects.length == 0) { return new HashMap<>(); } Arrays.sort(objects); ModeCalc<T> calc = new ModeCalc<T>(objects[0]); for (T t : objects) { calc.checkMaxAppears(t); } return calc.getMode();}/** * Work like {@link #mode(Object...)}. */@SuppressWarnings(unchecked)public static <T> Map<T, Integer> mode(Comparator<? super T> c, T... objects) { Objects.requireNonNull(objects, objects must not be null); if (objects.length == 0) { return new HashMap<>(); } Arrays.sort(objects, c); ModeCalc<T> calc = new ModeCalc<T>(objects[0]); for (T t : objects) { calc.checkMaxAppears(t); } return calc.getMode();}/** * Work like {@link #mode(Object...)}. */public static Map<Integer, Integer> mode(int... numbers) { Objects.requireNonNull(numbers, numbers must not be null); if (numbers.length == 0) { return new HashMap<>(); } Arrays.sort(numbers); ModeCalc<Integer> calc = new ModeCalc<Integer>(numbers[0]); for (int t : numbers) { calc.checkMaxAppears(t); } return calc.getMode();}/** * Work like {@link #mode(Object...)}. */public static Map<Long, Integer> mode(long... numbers) { Objects.requireNonNull(numbers, numbers must not be null); if (numbers.length == 0) { return new HashMap<>(); } Arrays.sort(numbers); ModeCalc<Long> calc = new ModeCalc<>(numbers[0]); for (long t : numbers) { calc.checkMaxAppears(t); } return calc.getMode();}/** * Work like {@link #mode(Object...)}. */public static Map<Double, Integer> mode(double... numbers) { Objects.requireNonNull(numbers, numbers must not be null); if (numbers.length == 0) { return new HashMap<>(); } Arrays.sort(numbers); ModeCalc<Double> calc = new ModeCalc<Double>(numbers[0]); for (double t : numbers) { calc.checkMaxAppears(t); } return calc.getMode();}/** * Work like {@link #mode(Object...)}. */public static Map<Float, Integer> mode(float... numbers) { Objects.requireNonNull(numbers, numbers must not be null); if (numbers.length == 0) { return new HashMap<>(); } Arrays.sort(numbers); ModeCalc<Float> modeCalc = new ModeCalc<Float>(numbers[0]); for (float t : numbers) { modeCalc.checkMaxAppears(t); } return modeCalc.getMode();}/** * Work like {@link #mode(Object...)}. */public static Map<String, Integer> mode(String... strings) { Objects.requireNonNull(strings, strings must not be null); if (strings.length == 0) { return new HashMap<>(); } Arrays.sort(strings); ModeCalc<String> state = new ModeCalc<>(strings[0]); for (String t : strings) { state.checkMaxAppears(t); } return state.getMode();}private static class ModeCalc<T> { private int nTimesLastObjectAppears = 0; private int maxTimeObjectAppears = 0; private T prevObject; Map<T, Integer> mostAppearsObjects; public ModeCalc(T firstObjectInArray) { prevObject = firstObjectInArray; mostAppearsObjects = new HashMap<>(); } void checkMaxAppears(T currentObject) { if (currentObject.equals(prevObject)) { nTimesLastObjectAppears += 1; } else { addObjectToMap(); prevObject = currentObject; nTimesLastObjectAppears = 1; } } void addObjectToMap() { if (nTimesLastObjectAppears > maxTimeObjectAppears) { mostAppearsObjects.clear(); mostAppearsObjects.put(prevObject, nTimesLastObjectAppears); maxTimeObjectAppears = nTimesLastObjectAppears; } else if (nTimesLastObjectAppears == maxTimeObjectAppears) { mostAppearsObjects.put(prevObject, nTimesLastObjectAppears); } } Map<T, Integer> getMode() { // to check appears of last object of loop and add it to map addObjectToMap(); return mostAppearsObjects; }}}
General Java class to find mode
java;object oriented;statistics;data mining
null
_codereview.47519
I'm writing a script for others to use on their websites. I'd like to use jQuery in this script. Because I don't have control over what frameworks people use on their sites, I need to make sure jQuery is available and that it's version 1.8 or higher. Here's my take on it. Does anyone see anything I could/should be doing differently? Is there a better way of doing this?//start anon function for whole script;(function(){ var $, hasOwn = ({}).hasOwnProperty, //get ie version returns false if ie>=11 or not ie ieVersion = function(){ var v = 3, div = document.createElement('div'), all = div.getElementsByTagName('i'); while(div.innerHTML = '<!--[if gt IE '+(++v)+']><i></i><![endif]-->', all[0]); return (v > 4 ? v : ('documentMode' in document ? document.documentMode : false)); }(), //get which version of jQuery is currently added to the site jqVersion = function(){ return 'jQuery' in window && !!window.jQuery ? parseFloat(window.jQuery.fn.jquery) : false; }, //set the correct jquery version to use based on which version of ie is in use. Use an array in the case of one or more being down jqSrc = (!!ieVersion && ieVersion > 4 && ieVersion < 9) ? ['//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js', '//cdnjs.cloudflare.com/ajax/libs/jquery/1.11.0/jquery.min.js', '//ajax.aspnetcdn.com/ajax/jQuery/jquery-1.11.0.min.js'] : ['//ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js', '//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.0/jquery.min.js', '//ajax.aspnetcdn.com/ajax/jQuery/jquery-2.1.0.min.js'], //check jquery version and if it is above 1.8 use it, if not then get own version jqCheck = function(first){ var version = jqVersion(); if(!version || version < 1.8){ getScript(jqSrc.shift(), jqCheck); }else{ if(!!first){ $ = window.jQuery; }else{ $ = window.jQuery.noConflict(true); } load(); } }, //function to loop and load jquery script getScript = function(url, callback){ var script = document.createElement('script'), tag = document.getElementsByTagName('script')[0], done = false; script.type = 'text/javascript'; script.async = !0; script.src = url; script.onload = script.onreadystatechange = script.onerror = function(){ if(!done && (!this.readyState || this.readyState == 'loaded' || this.readyState == 'complete')){ done = true; if(typeof(callback) === 'function'){ callback.call(this); } script.onload = script.onreadystatechange = script.onerror = null; } }; tag.parentNode.insertBefore(script, tag); }, load = function(){ //Start script window.myGlobalFunction = new function(){ var privateVar = 'private', privateFunc = function(){ return true; }; this.publicVar = 'public'; this.publicFunc = function(){ return true; }; }; }; //make sure json is avaiable, if not add it if(!hasOwn.call(window, 'JSON') || !hasOwn.call(JSON, 'parse') || (typeof(JSON.parse) !== 'function')){ getScript('//cdnjs.cloudflare.com/ajax/libs/json3/3.3.1/json3.min.js', function(){ //all functions are built start by checking for jQuery and it's builder jqCheck(true); }); }else{ //all functions are built start by checking for jQuery and it's builder jqCheck(true); }})();
Dynamically loading jQuery when it's not available or version isn't high enough
javascript;jquery
null
_cogsci.16714
I have started to read a book called Vexed Texts by Pamela Protheroe and her belief is that images promotes illiteracy. There seems far too much evidence that pictures books aid children in a vast amount of ways, but it did make me wonder on children's dependency of what they see in comparison to what they imagine. My investigation is to find out children's understanding of the words and what they see internally without the visual cues.
Do pictures help young children read (understand meaning) better or does it give them a delayed sense of imagination when decoding information?
learning;language;communication;linguistics;visualization
null
_scicomp.19961
I have been looking for stability analysis of general reaction-diffusion problems, of the form$\frac{\partial u}{\partial t}=\nabla\cdot D\nabla u-k\,u$ , to be solved using the standard Finite Element in 2D with an explicit Euler time stepping. I haven't found any estimate or proof for the stability criteria for $\Delta t$ for this case, most of the literature seems to point to the solution of the Heat equation by Finite Differences in 1D.I would like to know if someone can point me how to find the stability criterion in this case, especially for quadrilateral elements.
Stability analysis for explicit time discretization in the Finite Element Method
finite element;numerical analysis;stability
null
_unix.61862
Imagine a shell script on the remote server as#!/bin/bashrm /test.xHow can I (if possible) to execute this script from my local machine to delete /test.x file on my local machine. Obviously, the solution should be with something like ssh authorization, but without downloading the script file from the remote server.In fact, I want to use the remote script as a provider of shell commands to be run on the local machine.
Executing a shell script from remote server on local machine
shell;ssh;shell script;remote
null
_webapps.52576
While testing my iOS app, I used some event names that I have since removed and never actually deployed.Now, my Events Overview page in Google Analytics is cluttered with old event category/action/label names. (https://developers.google.com/analytics/devguides/collection/ios/v3/events)Is there any way to remove them?
Delete old events in Google Analytics
google analytics
null
_unix.178385
I've installed VMware player 64bit version 7 (upgraded from 6) for both Windows 7 and CentOS 6.5I run usually centOS and Fedora as guest VM.I've observed, that the RAM usage goes up (as it should) on Host OS when I spin multiple guest VM and also when I spin enterprise applications (IBM Websphere suite) on those guest VM.On CentOS as host, I don't see RAM release after I shutdown guest VM or shutdown application on guest VM. Even after 15 20 min unless I reboot the host OS.In comparison, when using Windows 7 as host, RAM release almost instantly.These are same guest VM that I use on both Host OS.The behavior was same on VMware player version 6.Is VMware player is better optimized for Win than Linux? If not, what measure can I take to have RAM release when using CentOS as host?
Why VMware player doesn't release the memory when running on Linux while in Windows it does?
vmware
null
_codereview.155850
I have a general value called Seed which is required to multiple class. But those class aren't dependent of the class which declare it.class Game { class Settings { public static float Seed = 1337; }}And some class need a Seed value to work. I take the class Noise as example here.class Noise { private static float _seed;}A solution would be to use Game.Settings.Seed to know the value into the class Noise. But what if one day I decide to take all the Noise class to use it in an other project. The code won't compile because there is probably not a Game.Settings.Seed declared in the other project obviously.A other way would be to set as public field in the Noise class.class Noise { public static float Seed;}So in this way, Game which know he need to use Noise class, will set Seed field before doing anything with this class.But I don't like it too, in this case this is about a float, so that not really a problem, but what about an object that need to be declared, which means Noise class need to implement a verification about itself.class Noise { private static float _seed; private static bool _isSeedDeclared; public static void SetSeed(int seed){ _seed = seed; _isSeedDeclared = true; } public int GetValue(int x, int z){ CheckSettings(); return computedValue; //to calculate computedValue, I need Seed value } private void CheckSettings(){ if(!_isSeedDeclared) throw new Exception(You have to define Seed value.); }}This solution works but I'm not pleased about it. For non-nullable type I have to define an other variable to check, for a nullable class I can compare it to null. But anyway, I don't have only one parameter and I don't have only one class. I'm looking for an better way to implement it.
General static value required by multiple classes
c#
Okay, so there's lots going on in your question. Let's try and break it down.But what if one day I decide to take all the Noise class to use it in an other project. The code won't compile because there is probably not a Game.Settings.Seed declared in the other project obviously.What you're talking about here is decoupling. There are many different types of coupling in software design. You're on the right track, decoupling your classes from each other is a very good thing to do for many reasons, including the one you've described.In this specific example we're trying to decouple the Noise class from the Game.Settings class. You've really only got 2 options here. Constructor injection or Property injection. Both options are valid but they have pros and cons depending on your requirements. Any other option is either just a variation of these two (e.g. field injection, service or function injection) or won't really decouple things.So in this way, Game which know he need to use Noise class, will set Seed field before doing anything with this class.One of the pros of using constructor injection is to enforce that the Game class sets the seed on the Noise class before it can be used._noise = new Noise(Game.Settings.Seed);A other way would be to set as public field in the Noise class.This is a form of property injection. The downside is that you can only enforce things by using exceptions at runtime. In some cases it makes sense, but from what I've seen I don't think this is your best choice.For non-nullable type I have to define an other variable to check, for a nullable class I can compare it to null.Actually, C# has nullable types for exactly this situation. So you could convert this code:private static float _seed;private static bool _isSeedDeclared;into this:private static float? _seed;and when you want to use it you can do something like this:if(!_seed.HasValue) throw new Exception(You have to define Seed value.);But anyway, I don't have only one parameter and I don't have only one class. I'm looking for an better way to implement it.I agree, your question is a little more broad than this one class. It's more about the overall design of the system as a whole. The truth is there's no one size fits all answer, it depends.I believe part of the problem is the overuse of static. It's not really clear why the Noise class needs to use static at all. In particular, you're likely to run into all sorts of issues with the use of global static state as I suspect is the case.I'd seriously consider removing all the staticness from any classes that don't need it. Especially if they're also holding shared data. As usual, it depends, but you might be surprised how much simpler things become when you let go of that idea.
_unix.339282
I'm using tr and sed command to replace text in my file like this tr '\n' ' ' < afile.txt | sed '$s/ $/\n/' and as discussed here. Though running that on a big file will get my console spammed with output replaced text.So my need is to run the commands, but silence its output.My google search here and calling tr --help not helpful to me so I ask here.
How to run `tr` (translate command) and mute its output?
bash;text processing;tr
It's unlikely that you'd like to discard the output from the pipeline. It is more likely that you'd like to store it somewhere rather than having it flood your terminal.I think this is what you're looking for:$ tr '\n' ' ' < afile.txt | sed '$s/ $/\n/' >anotherfile.txtThis will put the result of the pipeline into the file anotherfile.txt rather than onto the terminal. You are then free to inspect it and to replace the original file with it (mv anotherfile.txt afile.txt) if this makes sense with what it is you're trying to achieve.The > at the end of the pipeline is an output redirection that will redirect the standard output stream of sed into the specified file. It works in the opposite way of the input redirection < that is used earlier in the pipeline to send the contents of afile.txt into the standard input stream of tr.
_cogsci.10325
While reading Daniel Kahneman's Thinking, Fast and Slow I've been stuck on the claim that Linda case and Dinnerware case have the same structure.Linda problem:Linda is thirty-one years old, single, outspoken, and very bright. She majored in philosophy. As a student, she was deeply concerned with issues of discrimination and social justice, and also participated in antinuclear demonstrations.Which alternative is more probable?Linda is a bank teller.Linda is a bank teller and is active in the feminist movement.It is well-known that the majority of respondents chooses the second options (as most plausible, though the original question is about probability).The Dinnerware case:Being presented two sets of dinnerware:Set A: 40 pieces / Set B: 24 piecesDinner plates: 8, all in good condition / 8, all in good condition Soup/salad bowls: 8, all in good condition / 8, all in good condition Dessert plates: 8, all in good condition / 8, all in good condition Cups: 8, 2 of them broken / NONE Saucers: 8, 7 of them broken / NONEIt is known that respondents tend to select Set B, though it is more beneficial to select set A.Here is the question: The dinnerware case is explained via the notion of 'averaging'. That is, person's System 1 (Kahneman's terminology) performs some kind of averaging and goes to conclusion, that as Set B items are not broken and in average cost more, then the whole Set B shall be preferred.From the perspective of economic theory, this result is troubling: the economic value of a dinnerware set [...] is a sum-like variable. I.e. pure summation shall be performed where averaging and subsequent assessment is carried out.Then,The Linda problem and the dinnerware problem have exactly the same structure (??). Probability, like economic value, is a sum-like variable, as illustrated by this example: probability (Linda is a teller) = probability (Linda is feminist teller) + probability (Linda is non-feminist teller) System 1 averages instead of adding, so when the non-feminist bank tellers are removed from the set, subjective probability increases.Here is my difficulty: I do not see how the 'averaging' notion applies to the Linda problem. When I myself think about Linda question, I do not realize that try to average something, I just want to construct something that fits my stereotypes. Otherwise, when I think about dinnerware, I agree that subconsciously try to maximize the average price of item.
Thinking Fast and Slow: Similarity of Linda problem and Dinnerware case
cognitive psychology;bias
null
_softwareengineering.348257
I am implementing the repository pattern in my application.The repository will connect to an API to download orders from an external API.The API that I am connecting to has a separate endpoint to get the list of Orders and a separate endpoint to get the Items against that order.Where should the marriage of OrderItems and Orders happen? Should the GetOrders() function in my repository get orders as well as items, returning it back to the service with both orders and items. Or should the service layer be responsible for running GetOrders() and GetOrderItems() and joining these together?Hope that makes sense!
Should my repository or service be responsible for joining multiple API calls into one object
api;repository
null
_webmaster.30627
If a website a called foo.com has the following css,#LinkBuilder{background:url(www.LoremEpsum.com);}and the css id LinkBuilder is actually not getting used anywhere in the html of foo.com, would Google bot crawl it as a backlink from foo.com to LoremEpsum.com and LoremEpsum.com gets the link juice from foo.com without getting displayed on the website?Please help out. Thanks
Does Google bot crawl unused tags?
google;googlebot
First of all, that's a background property, so I'm not sure why google would think it's a link.However, assuming that you meant does it index the background image. I'm going to assume no, because if you look at their image guidelines, you will find that they make no reference to background images, and all of their advice seems to be geared towards the <img> tag.